<?php
/**
 * Created by PhpStorm.
 * User: kwibon
 * Date: 2019/4/23
 * Time: 9:55
 */

namespace app\admin\controller;

use app\api\model\TripActiveHotel;
use \think\Cookie;
use think\Exception;
use think\Db;
use think\Cache;
use app\admin\model\Trip as tripModel;
use app\api\model\Trip as TripApiModel;
use app\admin\model\Tripcustomer as tripcustomerModel;
use app\admin\model\Schedule as scheduleModel;
use app\admin\model\Active as activeModel;
use app\api\controller\GoogleMap;
use app\api\model\Poi as PModel;
use app\api\controller\KbxOther;
use app\api\controller\KbxToken;
use app\api\controller\Trip as TripApi;
use app\api\controller\Member as MemberApi;
use app\api\controller\Common;
use app\admin\model\Dayprice as DaypriceModel;
use app\api\model\Standard as SDModel;
use app\admin\controller\Product as ProductCtl;
use think\Request;
use think\Validate;

class Quicktrip extends User
{
    public $goodsurl = 'https://c.kuaibangxing.com/quick_help_wap1/#/show/';

    //定义前置方法
    protected $beforeActionList = [
        'checkIsTemplateTrip'=>[
            'only'=>'savetripcustomerdata,changeinfo,changetitle,savedaydescription,getactivedata,getpointdistance,setactive,deletepoi,deleteday,addactive,addday,setticketstatus,updateactiveinfo,tripimport,tripconfig,dragsort,changeactiveday'
        ]
    ];

    //快速定制列表
    public function index()
    {
        $post = $this->request->post();
        //分页bug处理
        $temp_page=request()->param('page');
        if(isset($temp_page)){
            //条件从缓存取出
            $post=Cookie::get('quicktriplist');
        }else{
            //把条件写入缓存
            Cookie::set('quicktriplist',$post);
        }

        $where = [];
        $where['t.use_type'] = 2;
        if (isset($post['tripname']) && !empty($post['tripname'])) {
            $where['t.name|t.id|t.people|t.days|t.citys'] = ['like', '%' . trim($post['tripname']) . '%'];
        }
        if (isset($post['admin_id']) && !empty($post['admin_id'])) {
            $where['t.adminid'] = $post['admin_id'];
        }
        if (isset($post['isPaid']) && $post['isPaid']!=="") {
            $where['t.isConfirm'] = 1;
            $where['t.isPaid'] = $post['isPaid'];
        }
        if (isset($post['is_template']) && $post['is_template']!=="") {
            $where['t.is_template'] = $post['is_template'];
        }

        $trip = Db::name('trip')
            ->alias("t")
            ->join("admin a",'a.id=t.adminid',"left")
            ->where($where)
            ->field("t.*,a.nickname as admin")
            ->order('create_time desc')
            ->paginate(20);

        $this->assign('trip',$trip);
        $this->assign('wherelist',$post);
        //获取顶定制师列表
        $adminList = db("admin")->field("id,nickname")->select();
        $this->assign('adminList',$adminList);

        return $this->fetch();
    }

    //详细定制页
    public function tripmake(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        //更新门票信息
        $model = new tripModel();
        $weekarray=array("日","一","二","三","四","五","六");
        $trip = [];
        if($id > 0) {
            $trip = $model->where("id",$id)->find();
            if(empty($trip)) return $this->error('定制行程不存在');
            $trip['start_go_time'] = $trip['start_go_time']>0 ? date("Y-m-d",$trip['start_go_time']) : '';
            $tripid = $id;
            $schedule = db("schedule")->where("groupid",$id)->order("displayorder asc")->select();

            $day = 1;
            //默认显示遮罩
            $trip['is_show_shadow'] = 1;
            foreach ($schedule as $k=>$v) {
                $schedule_id = $v['id'];
                $active = db("active")
                    ->where("groupid",$schedule_id)
                    ->order("displayorder asc")
                    ->field("id,title,poiname,poiid,cityid,activeType,airport_lat,airport_lng")
                    ->select();

                if(!empty($active)){
                    foreach ($active as $k_a=>$v_a) {
                        if(!empty($v_a['cityid']) && $v_a['cityid']>0){
                            $where['deleted'] = 0;
                            $where['groupid'] = $v_a['cityid'];

                            $poiArr = [];
                            if($v_a['activeType']==1){//POI
                                $where['typeid'] = ['in',[1,2,3,4,6]];//1景点，3演出赛事，4限时活动，6其他，11美食
                                $poiArr = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name")->select();
                            }elseif($v_a['activeType']==2 || $v_a['activeType']==3){//接机 送机
                                $airportData = $this->kbxGetAirport($v_a['cityid']);
                                $airport = [];
                                foreach ($airportData as $k_air=>$v_air) {
                                    $airportName = (isset($v_air['nameen']) && $v_air['nameen']!=='') ? $v_air['name']."(".$v_air['nameen'].")" : $v_air['name'];
                                    $airport[] = ['id'=>$v_air['id'],'name'=>$airportName];
                                    $poiArr = $airport;
                                }
                            }elseif($v_a['activeType']==4){//酒店
                                $where['typeid'] = 5;//酒店
                                $poiArr = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name")->select();
                            }elseif($v_a['activeType']==5){//特色体验

                            }elseif($v_a['activeType']==6){//其他

                            }elseif($v_a['activeType']>10){
                                $where['typeid'] = $v_a['activeType'];
                                $poiArr = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name")->select();
                            }

                            $active[$k_a]['poiArr'] = $poiArr;

                            //加入距离
                            $activeDistance = $this->getActiveDistance($k_a,$active);
                            $active[$k_a]['limit'] = $activeDistance;
                        }else{
                            $active[$k_a]['poiArr'] = [];
                        }
                    }
                }

                $schedule[$k]['active'] = $active;
                $schedule[$k]['dayNum'] = $day;
                $schedule[$k]['week'] = "周".$weekarray[date("w",strtotime($v['time']))];

                $_trans_type_arr = [];
                if(!empty($v['transport_typeids'])){
                    //不显示遮罩
                    $trip['is_show_shadow'] = 0;
                    $trans_type_arr = explode(",",$v['transport_typeids']);
                    if(!empty($trans_type_arr)){
                        foreach ($trans_type_arr as $value){
                            $trans_type_item = [
                                'id'=>$value,
                                'title'=>$this->getTransportTitle($value),
                            ];
                            $_trans_type_arr[] = $trans_type_item;
                        }
                    }
                }
                $schedule[$k]['transportList'] = $_trans_type_arr;

                $day++;
            }
            //核价数据
            $this->assign('totalHotelPrice',$trip['totalHotelPrice']);
            $this->assign('totalAirportPrice',$trip['totalAirportPrice']);
            $this->assign('totalDrivePrice',$trip['totalDrivePrice']);
            $this->assign('totalTransPrice',$trip['totalTransPrice']);
            $this->assign('airportPrice_btn',$trip['airportPrice_btn']);
            $this->assign('hotelPrice_btn',$trip['hotelPrice_btn']);
            $this->assign('drivePrice_btn',$trip['drivePrice_btn']);
            $this->assign('carPrice_btn',$trip['carPrice_btn']);

            $this->assign('schedule',$schedule);
            //生成dayprice记录
            $this->createDayPriceData($schedule);
            //当前定制处于未锁状态方可更新
            if($trip['isLocked']<1){
                //更新门票信息
                $this->sumTicketDetailAndPrice($tripid);
            }
            $priceTable = $this->priceTable($tripid);
            $transportData = $this->getOrderSystemTransportData($trip['activitiesSnap']);
            $tripData = $this->packagePricingData($priceTable,$transportData);
            $renderPriceData = $this->getTripPriceTableData($tripData);
            //var_dump(json_encode($renderPriceData));exit;
            $this->assign('priceTable',$renderPriceData);
            //获取用车核价
            $totalCarPriceCNY = 0;
            if(!empty($trip['car_price_section'])){
                $car_price_section = json_decode($trip['car_price_section'],true);
                //获取汇率
                $exchange = db('exchange')->where(['currency_code'=>$trip['costCurrency']])->find();
                if(!empty($exchange)){
                    foreach ($car_price_section as $car_price){
                        $totalCarPriceCNY += ceil($car_price*$exchange['exchange_rate']);
                    }
                }
            }
            $this->assign('totalCarPriceCNY',$totalCarPriceCNY);
            //行程cdk
            $tripcdk = db('tripcdk')->where(['trip_id'=>$id,'isdelete'=>0,'state'=>1])->find();
            if(!empty($tripcdk)) $trip['cdk'] = $tripcdk['CDK'];
        }else{
            $this->assign('airportPrice_btn',0);
            $this->assign('hotelPrice_btn',0);
            $this->assign('drivePrice_btn',0);
            $this->assign('carPrice_btn',0);
            $tripid = 0;
        }
        $where_city['type'] = "CITY";
        $where_city['deleted'] = 0;
        //按照中文名称排序
        $city_order = new \think\db\Expression("CONVERT(name USING gbk) asc");
        $city = db("city")->where($where_city)->field("id,name")->order($city_order)->select();
        $tripcustomer = db("tripcustomer")->where("tripid",$tripid)->find();

        $this->assign('city',$city);
        $this->assign('tripid',$tripid);
        $this->assign('trip',$trip);
        $this->assign('customer',$tripcustomer);
        //新建poi所需城市列表
        $ourcity = Db::name('city')->where(['deleted'=>0,'groupid'=>['neq',0]])->field('id,concat(name,"(",eng_name,")") as name')->order("sort_weight desc")->select();
        $this->assign('ourcity',$ourcity);

        //扩展包车
        $transport = $this->getTransportTitle();
        $this->assign('transport',$transport);


        //获取订单的来源列表
        $originList = (new KbxOther())->kbx_origin_list();
        $this->assign('originList',$originList);
        //渲染行程价格数据
        //获取国家电话区号
        $phoneCodeList = (new TripApi())->getCountryPhoneCode();
        $this->assign('phoneCodeList',$phoneCodeList);

        //货币类型
        $currencyCodeList = (new Common())->getCurrencyListByCity();
        $this->assign("currencyCodeList",json_encode($currencyCodeList));
        //获取税率
        $exchangeList = db('exchange')->select();
        $this->assign("exchangeList",json_encode($exchangeList));

        //POI分类 前期做了部分拆分 以至于需要单独设计
        $poiClassifyList = (new ProductCtl())->getPoiClassifyList();
        $global_active_type_arr = (new ProductCtl())->getGlobalActiveTypeList();

        $this->assign("poiClassifyList",$poiClassifyList);
        $this->assign("global_active_type_arr",json_encode($global_active_type_arr));

        return $this->fetch();
    }

    //提交信息创建行程
    public function info(){
        if($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post();

            $tripData = [];
            if(!empty($post['name'])){//方案名称
                $tripData['name'] = $post['name'];
            }
            if(!empty($post['days'])){//天数
                $tripData['days'] = $post['days'];
            }
            if(!empty($post['start_go_time'])){//出行日期
                $tripData['start_go_time'] = strtotime($post['start_go_time']);
            }
            if(!empty($post['carType'])){//车辆选择
                $tripData['carType'] = $post['carType'];
            }

            if(!empty($post['adult'])){//出行人数  成人
                $tripData['adult'] = $post['adult'];
            }else{
                $tripData['adult'] = 0;
            }
            if(!empty($post['child'])){//出行人数  儿童
                $tripData['child'] = $post['child'];
            }else{
                $tripData['child'] = 0;
            }
            $tripData['people'] = $tripData['adult']+$tripData['child'];

            if(!empty($post['start_city'])){//出发城市
                $tripData['start_city'] = $post['start_city'];
                $city = db("city")->where("id",$post['start_city'])->find();
                $post['from_kbx_id'] = $city['kbx_id'];//商机字段：目的地城市mongo_id
            }
            if(!empty($post['end_city'])){//目的地城市
                $tripData['end_city'] = $post['end_city'];
            }

            $tripData['quickFlag'] = 1;
            $tripData['use_type'] = 2;

            $adminid = Cookie::get('admin');
            $tripData['adminid'] = $adminid;

            //客户信息
            $customerData = [];
            if(!empty($post['nickname'])){//姓名
                $customerData['nickname'] = $post['nickname'];
            }
            if(!empty($post['phone'])){//电话
                $customerData['phone'] = $post['phone'];
            }
            if(!empty($post['wechat'])){//微信
                $customerData['wechat'] = $post['wechat'];
            }
            if(!empty($post['email'])){//email
                $customerData['email'] = $post['email'];
            }
            if(!empty($post['age'])){//年龄
                $customerData['age'] = $post['age'];
            }
            if(!empty($post['source'])){//来源
                $customerData['source'] = $post['source'];
            }
            if(!empty($post['type'])){//性质
                $customerData['type'] = $post['type'];
                if($post['type']=='person'){
                    $post['bigGroup'] = false;
                }else{
                    $post['bigGroup'] = true;
                }
            }

            $model=new tripModel();
            if(false == $model->allowField(true)->save($tripData)) {
                return $this->error('新增失败');
            } else {
                $tripid = Db::name('trip')->getLastInsID();

                //添加客户信息
                $customerData['tripid'] = $tripid;
                $tripcustomerModel = new tripcustomerModel();
                $tripcustomerModel->allowField(true)->save($customerData);

//                //增加商机
//                $KbxOrder = new KbxOrder();
//                $bus_id = $KbxOrder->enterBusOpportunities($post);
//                db("trip")->where("id",$tripid)->update(['opportunity_id'=>$bus_id]);

                $scheduleModel = new scheduleModel();
                $days = $post['days'];
                $date = $post['start_go_time'];
                $nowtime = time();
                for ($i=1;$i<=$days;$i++){
                    //添加schedule
                    $daysData = [];
                    $daysData['groupid'] = $tripid;
                    $daysData['time'] = $date;
                    $daysData['displayorder'] = $i;
                    $daysData['create_time'] = $nowtime;
                    $daysData['update_time'] = $nowtime;

                    $scheduleModel->allowField(true)->create($daysData);
                    $scheduleid = Db::name('schedule')->getLastInsID();
                    $date = date("Y-m-d",strtotime("+1 day",strtotime($date)));

                    //添加active
                    $activeData = [];
                    $activeData['typeid'] = 3;
                    $activeData['groupid'] = $scheduleid;
                    $activeData['displayorder'] = 1;
                    $activeData['create_time'] = $nowtime;
                    $activeData['update_time'] = $nowtime;

                    $activeModel = new activeModel();
                    $activeModel->allowField(true)->create($activeData);
                }

                return $this->success('新增成功',"", $tripid);
            }
        } else {
            $where['type'] = "CITY";
            $where['deleted'] = 0;

            $city = db("city")->where($where)->field("id,name")->select();

            $cityJson = json_encode($city,JSON_UNESCAPED_UNICODE);

            $this->assign('city',$city);
            $this->assign('cityJson',$cityJson);

            //获取订单的来源列表
            $originList = (new KbxOther())->kbx_origin_list();
            $this->assign('originList',$originList);
            return $this->fetch();
        }
    }

    //导入行程创建
    public function importInfo(){
        if($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post();

            //导入行程id串
            if(!empty($post['tripids'])){
                $tripids = $post['tripids'];
                $tripsArr = explode(",",$tripids);
            }else{
                $tripsArr = [];
            }
            if(!empty($post['productids'])){
                $productids = $post['productids'];
                $productsArr = explode(",",$productids);
            }else{
                $productsArr = [];
            }
            if(empty($tripsArr) && empty($productsArr)){
                return $this->error("至少要选择一个行程导入！");
            }

            $tripData = [];
            if(!empty($post['name'])){//方案名称
                $tripData['name'] = $post['name'];
            }
            if(!empty($post['days'])){//天数
                $tripData['days'] = $post['days'];
            }
            if(!empty($post['start_go_time'])){//出行日期
                $tripData['start_go_time'] = strtotime($post['start_go_time']);
            }
            if(!empty($post['carType'])){//车辆类型
                $tripData['carType'] = $post['carType'];
            }
            if(!empty($post['adult'])){//出行人数  成人
                $tripData['adult'] = $post['adult'];
            }else{
                $tripData['adult'] = 0;
            }
            if(!empty($post['child'])){//出行人数  儿童
                $tripData['child'] = $post['child'];
            }else{
                $tripData['child'] = 0;
            }
            $tripData['people'] = $tripData['adult']+$tripData['child'];

            if(!empty($post['start_city'])){//出发城市
                $tripData['start_city'] = $post['start_city'];
                $city = db("city")->where("id",$post['start_city'])->find();
                $post['from_kbx_id'] = $city['kbx_id'];//商机字段：目的地城市mongo_id
            }
            if(!empty($post['end_city'])){//目的地城市
                $tripData['end_city'] = $post['end_city'];
            }

            $tripData['quickFlag'] = 1;
            $tripData['use_type'] = 2;

            $adminid = Cookie::get('admin');
            $tripData['adminid'] = $adminid;

            //客户信息
            $customerData = [];
            if(!empty($post['nickname'])){//姓名
                $customerData['nickname'] = $post['nickname'];
            }
            if(!empty($post['phone'])){//电话
                $customerData['phone'] = $post['phone'];
            }
            if(!empty($post['wechat'])){//微信
                $customerData['wechat'] = $post['wechat'];
            }
            if(!empty($post['email'])){//email
                $customerData['email'] = $post['email'];
            }
            if(!empty($post['age'])){//年龄
                $customerData['age'] = $post['age'];
            }
            if(!empty($post['source'])){//来源
                $customerData['source'] = $post['source'];
            }
            if(!empty($post['type'])){//性质
                $customerData['type'] = $post['type'];
                if($post['type']=='person'){
                    $post['bigGroup'] = false;
                }else{
                    $post['bigGroup'] = true;
                }
            }

            $model = new tripModel();
            if(false == $model->allowField(true)->save($tripData)) {
                return $this->error('新增失败');
            } else {
                $tripid = Db::name('trip')->getLastInsID();

                //添加客户信息
                $customerData['tripid'] = $tripid;
                $tripcustomerModel = new tripcustomerModel();
                $tripcustomerModel->allowField(true)->save($customerData);

//                //增加商机
//                $KbxOrder = new KbxOrder();
//                $bus_id = $KbxOrder->enterBusOpportunities($post);
//                db("trip")->where("id",$tripid)->update(['opportunity_id'=>$bus_id]);

                $start_date = $post['start_go_time'];
                $res = $this->importOldTripByTripIds($tripsArr,$productsArr,$tripid,$start_date);
                if($res){
                    return $this->success('新增成功',"",$tripid);
                }else{
                    return $this->error('新增失败');
                }
            }
        }
    }

    //更新信息
    public function changeInfo(){
        if($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post();

            if(empty($post['tripid']) || $post['tripid']<=0){
                return $this->error("请求错误，缺少tripid");
            }

            $tripid = $post['tripid'];

            $oldData = db("trip")->where("id",$tripid)->find();

            $tripData = [];
            if(!empty($post['name'])){//方案名称
                $tripData['name'] = $post['name'];
            }
            if(!empty($post['days'])){//天数
                if($post['days']>$oldData['days']){
                    $tripData['days'] = $post['days'];
                }
            }
            if(!empty($post['start_go_time'])){//出行日期
                $tripData['start_go_time'] = strtotime($post['start_go_time']);
            }

            if(!empty($post['carType'])){//车辆选择
                $tripData['carType'] = $post['carType'];
            }

            if(!empty($post['adult'])){//出行人数  成人
                $tripData['adult'] = $post['adult'];
            }else{
                $tripData['adult'] = 0;
            }
            if(!empty($post['child'])){//出行人数  儿童
                $tripData['child'] = $post['child'];
            }else{
                $tripData['child'] = 0;
            }
            $tripData['people'] = $tripData['adult']+$tripData['child'];

            if(!empty($post['start_city'])){//出发城市
                $tripData['start_city'] = $post['start_city'];
                $city = db("city")->where("id",$post['start_city'])->find();
                $post['from_kbx_id'] = $city['kbx_id'];//商机字段：目的地城市mongo_id
            }
            if(!empty($post['end_city'])){//目的地城市
                $tripData['end_city'] = $post['end_city'];
            }

            $tripData['quickFlag'] = 1;

            $model=new tripModel();
            if(false == $model->allowField(true)->save($tripData,['id'=>$tripid])) {
                return $this->error('修改失败');
            } else {
                //日期重排 保证顺序
                $this->revertDay($tripid);

                return $this->success('修改成功');
            }
        } else {
            return $this->error('没有数据');
        }
    }

    //删除定制
    public function deltrip()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if(false == Db::name('trip')->where('id',$id)->delete()) {
            return $this->error('删除失败');
        } else {
            return $this->success('删除成功');
        }
    }

    //ajax增加天数
    public function addDay(){
        $post = $this->request->post();
        $tripid = $post['tripid'];
        $nowtime = time();

        $days = db("schedule")->where("groupid",$tripid)->count("id");
        $days = $days+1;
        $updateData['days'] = $days;

        $tripModel = new tripModel();

        if(false == $tripModel->allowField(true)->save($updateData,['id'=>$tripid])) {
            return $this->error('新增失败');
        } else {
            $schedule = db("schedule")->where("groupid",$tripid)->order("displayorder desc")->find();
            $scheduleModel = new scheduleModel();
            $daysData = [];
            $daysData['groupid'] = $tripid;
            $daysData['time'] = date("Y-m-d",strtotime("+1 day",strtotime($schedule['time'])));
            $daysData['displayorder'] = $schedule['displayorder']+1;
            $daysData['create_time'] = $nowtime;
            $daysData['update_time'] = $nowtime;
            $scheduleModel->allowField(true)->create($daysData);
            $schedule_id = Db::name('schedule')->getLastInsID();

            //添加active
            $activeData = [];
            $activeData['typeid'] = 3;
            $activeData['groupid'] = $schedule_id;
            $activeData['displayorder'] = 1;
            $activeData['create_time'] = $nowtime;
            $activeData['update_time'] = $nowtime;
            $activeModel = new activeModel();
            $activeModel->allowField(true)->create($activeData);
            $active_id = Db::name('active')->getLastInsID();

            $where_city['type'] = "CITY";
            $where_city['deleted'] = 0;

            $city = db("city")->where($where_city)->field("id,name")->select();

            $resData = [
                'days'=>$days,
                'schedule_id'=>$schedule_id,
                'active_id'=>$active_id,
                'displayorder'=>$daysData['displayorder'],
                'time'=>$daysData['time'],
                'city'=>$city
            ];

            return $this->success("新增成功","",$resData);
        }
    }

    //ajax获取POI
    public function getpoi(){
        $post = $this->request->post();
        $active_id = $post['active_id'];
        $cityid = $post['cityid'];

        $where['deleted'] = 0;
        $where['groupid'] = $cityid;
        $classifyIds = db('classify')->where(['is_use'=>1,'classify_id'=>['neq',5]])->column('classify_id');//排除酒店选项
        $where['typeid'] = ['in',$classifyIds];

        $poi = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name")->select();
        $city = db("city")->where("id",$cityid)->field("name")->find();

        $activeModel = new activeModel();

        $updateData["cityid"] = $cityid;
        $updateData["cityname"] = $city['name'];
        $updateData["poiid"] = 0;
        $updateData["poiname"] = '';
        $activeModel->allowField(true)->save($updateData,['id'=>$active_id]);

        $trip = db("trip")
            ->alias("t")
            ->join('schedule s','s.groupid=t.id')
            ->join('active a','s.id=a.groupid')
            ->where("a.id",$active_id)
            ->field("t.id")
            ->find();
        //统计城市
        $this->countCity($trip['id']);

        return $poi;
    }

    //ajax获取ActiveData  替代getpoi
    public function getActiveData(){
        $post = $this->request->post();
        $type_id = $post['type_id'];//类型
        $active_id = $post['active_id'];
        $city_id = $post['city_id'];

        $updateData = [];
        $resData = [];
        if($type_id==1){//POI
            $where['deleted'] = 0;
            $where['groupid'] = $city_id;
            $where['typeid'] = ['in',[1,2,3,4,6]];//1景点，3演出赛事，4限时活动，6其他，11美食
            $poi = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name")->select();
            $resData = $poi;
        }elseif($type_id==2 || $type_id==3){//2接机  3送机
            $airportData = $this->kbxGetAirport($city_id);
            $airport = [];
            foreach ($airportData as $k=>$v) {
                $airportName = (isset($v['nameen']) && $v['nameen']!=='') ? $v['name']."(".$v['nameen'].")" : $v['name'];
                $airport[] = ['id'=>$v['id'],'name'=>$airportName];
            }
            $resData = $airport;
        }elseif($type_id==4){//酒店
            $where['deleted'] = 0;
            $where['groupid'] = $city_id;
            $where['typeid'] = 5;
            $poi = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name")->select();
            $resData = $poi;
        }elseif($type_id==6){//其他

        }elseif($type_id>10){
            $where['deleted'] = 0;
            $where['groupid'] = $city_id;
            $where['typeid'] = $type_id;
            $poi = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name")->select();
            $resData = $poi;
        }

        $city = db("city")->where("id",$city_id)->field("name")->find();

        $updateData["cityid"] = $city_id;
        $updateData["cityname"] = $city['name'];
        $updateData["activeType"] = $type_id;
        $updateData["poiid"] = 0;
        $updateData["poiname"] = '';
        $updateData["poi_content"] = '';
        $updateData["content"] = '';

        $activeModel = new activeModel();
        $activeModel->allowField(true)->save($updateData,['id'=>$active_id]);

        $trip = db("trip")
            ->alias("t")
            ->join('schedule s','s.groupid=t.id')
            ->join('active a','s.id=a.groupid')
            ->where("a.id",$active_id)
            ->field("t.id")
            ->find();
        //统计城市
        $this->countCity($trip['id']);

        return $resData;
    }

    //ajax查询POI 反选城市
    public function getpoiByInput(){
        $post = $this->request->post();
        $name = isset($post['input']) ? $post['input'] : '';
        $city_id = $post['city_id'];

        $where['deleted'] = 0;
        $classify = db('classify')->where(['is_use'=>1])->select();
        $typeids = array_column($classify,'classify_id');
        $where['typeid'] = ['in',$typeids];//1景点，3演出赛事，4限时活动，6其他，11美食
        if($name!==''){
            $where['name|eng_name'] = ['like','%'.$name.'%'];
        }else{
            $where['groupid'] = $city_id;
        }

        $poi = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name,groupid")->select();

        return $poi;
    }

    //选择POI保存
    public function setpoi(){
        $post = $this->request->post();
        $active_id = $post['active_id'];

        $poiData = [];
        if(!empty($post['poiid']) && $post['poiid']>0){
            $poiid = $post['poiid'];
            $poi = db("poi")
                ->alias("p")
                ->join('city c','p.groupid=c.id',"left")
                ->where("p.id",$poiid)
                ->field("p.name,p.eng_name,p.groupid,p.typeid,p.introduce,p.thumb,c.name as cityname")
                ->find();
            $groupid = $poi['groupid'];
            $poiData['poiid'] = $poiid;
            $poiData['cityname'] = $poi['cityname'];
            $poiData['cityid'] = $poi['groupid'];
            $poiData['poitype'] = $poi['typeid'];
            $poiData['poi_content'] = $poi['introduce'];
            $poiData['poiImg'] = $poi['thumb'];
            $poiData['showthumb'] = 1;
            if(!empty($poi['eng_name']) && $poi['eng_name']!==''){
                $poiData['poiname'] = $poi['name']."（".$poi['eng_name']."）";
            }else{
                $poiData['poiname'] = $poi['name'];
            }
        }else{
            $poiData['poiid'] = '';
            $poiData['poitype'] = '';
            $poiData['poiname'] = '';
            $groupid = '';
        }

        $poiData['title'] = $poiData['poiname'];

        $activeModel = new activeModel();
        if(false == $activeModel->allowField(true)->save($poiData,["id"=>$active_id])) {
            return $this->error('修改失败');
        } else {
            return $this->success('修改成功','',['groupid'=>$groupid]);
        }
    }

    //选择active 保存   替代setpoi
    public function setActive(){
        $post = $this->request->post();
        $active_id = $post['active_id'];
        $type_id = $post['type_id'];//类型

        $activeData = [];
        $activeData['poiid'] = '';
        $activeData['poitype'] = '';
        $activeData['poiname'] = '';
        $groupid = '';
        $typeid = '';
        if(!empty($post['item_id']) && $post['item_id']>0){
            $global_active_type_arr = (new ProductCtl())->getGlobalActiveTypeList();
            if(in_array($type_id,$global_active_type_arr)){//1=POI，5=酒店
                $poiid = $post['item_id'];
                $poi = db("poi")
                    ->alias("p")
                    ->join('city c','p.groupid=c.id',"left")
                    ->where("p.id",$poiid)
                    ->field("p.name,p.eng_name,p.groupid,p.typeid,p.introduce,p.thumb,c.name as cityname")
                    ->find();
                $groupid = $poi['groupid'];
                if(in_array($poi['typeid'],[1,2,3,4,6])){
                    $typeid = 1;
                }elseif($poi['typeid']==5){
                    $typeid = 4;
                }else{
                    $typeid = $poi['typeid'];
                }
                $activeData['poiid'] = $poiid;
                $activeData['cityname'] = $poi['cityname'];
                $activeData['cityid'] = $poi['groupid'];
                $activeData['poitype'] = $poi['typeid'];
                $activeData['activeType'] = $typeid;
                $activeData['poi_content'] = $poi['introduce'];
                $activeData['content'] = '';
                $activeData['poiImg'] = implode(',',array_slice(array_filter(explode(',',$poi['thumb'])),0,2));
                $activeData['showthumb'] = 1;
                if(!empty($poi['eng_name']) && $poi['eng_name']!==''){
                    $activeData['poiname'] = $poi['name']."（".$poi['eng_name']."）";
                }else{
                    $activeData['poiname'] = $poi['name'];
                }
            }elseif($type_id==2 || $type_id==3){//接机  送机
                $activeArr = db("active")->where("id",$active_id)->field("cityid")->find();
                $airportData = $this->kbxGetAirport($activeArr['cityid']);
                foreach ($airportData as $k=>$v) {
                    if($v['id']==$post['item_id']){
                        $activeData['airport_lat'] = $v['location']['lat'];
                        $activeData['airport_lng'] = $v['location']['lng'];
                    }
                }
                $activeData['poiid'] = $post['item_id'];
                $activeData['poiname'] = $post['item_text'];
                $activeData['content'] = '';
                $activeData['poi_content'] = '';
                $activeData['airport_lnglat'] = $post['item_text'];
            }
        }

        $activeData['title'] = $activeData['poiname'];

        $activeModel = new activeModel();
        if(false == $activeModel->allowField(true)->save($activeData,["id"=>$active_id])) {
            return $this->error('修改失败');
        } else {
            return $this->success('修改成功','',['groupid'=>$groupid,'typeid'=>$typeid]);
        }
    }

    //ajax增加一个active
    public function addActive(){
        $post = $this->request->post();
        $schedule_id = $post['schedule_id'];
        $activeType = !empty($post['activeType']) ? $post['activeType'] : 1;
        $cityid = !empty($post['cityid']) ? $post['cityid'] : 0;
        $nowtime = time();
        $active = db("active")->where("groupid",$schedule_id)->order("displayorder desc")->find();

        if(!empty($active)){
            $displayorder = $active['displayorder']+1;
        }else{
            $displayorder = 1;
        }

        //添加active
        $activeData = [];

        $activeData['activeType'] = $activeType;
        if($activeType==1){//1POI，2接机，3送机，4酒店，5特色体验，6其他
            $activeData['typeid'] = 3;//1机场，2城市，3POI，5跟团游，6商品，4其他',
        }elseif($activeType==2 || $activeType==3){
            $activeData['typeid'] = 1;
        }elseif($activeType==4){
            $activeData['typeid'] = 3;
        }elseif($activeType==6){
            $activeData['typeid'] = 4;
        }else{
            $activeData['typeid'] = 5;
        }

        $activeData['groupid'] = $schedule_id;
        if($cityid>0){
            $activeData['cityid'] = $cityid;
        }
        $activeData['displayorder'] = $displayorder;
        $activeData['create_time'] = $nowtime;
        $activeData['update_time'] = $nowtime;

        $activeModel = new activeModel();
        if(false == $activeModel->allowField(true)->create($activeData)) {
            return $this->error('插入失败');
        } else {
            $activeid = Db::name('active')->getLastInsID();
            return $this->success("插入成功","",$activeid);
        }
    }

    //拖拽排序页面
    public function dragsort(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if($id > 0) {
            $tripid = $id;
            $schedule = db("schedule")->where("groupid",$id)->order("displayorder asc")->field("id,title,time")->select();
            foreach ($schedule as $k=>$v) {
                $active = db("active")
                    ->where("groupid",$v['id'])
                    ->order("displayorder asc")
                    ->field("id,poiname")
                    ->select();

                $schedule[$k]['active'] = $active;
            }
            foreach ($schedule as $key=> $value){
                $schedule[$key]['dayNum'] = $key+1;
            }
            $this->assign('schedule',$schedule);
        }else{
            $schedule = [];
            $tripid = 0;
        }
//        var_dump($schedule);exit;
        $this->assign('schedule',$schedule);
        $this->assign('tripid',$tripid);

        return $this->fetch();
    }

    //ajax修改schedule标题
    public function changeTitle(){
        $post = $this->request->post();
        $schedule_id = $post['schedule_id'];
        $title = $post['title'];

        if(false == db('schedule')->where('id', $schedule_id)->update(['title' =>$title])) {
            return $this->error('修改失败');
        }else{
            return $this->success('修改成功');
        }
    }

    //ajax删除POI
    public function deletePoi(){
        $post = $this->request->post();
        $active_id = $post['active_id'];
        $active = db("active")->where("id",$active_id)->find();

        $trip = db("trip")
            ->alias("t")
            ->join('schedule s','s.groupid=t.id')
            ->join('active a','s.id=a.groupid')
            ->where("a.id",$active_id)
            ->field("t.id")
            ->find();

        if(!empty($active)){
            if(false == db("active")->where('id',$active_id)->delete()) {
                return $this->error('删除失败');
            } else {
                //统计城市
                $this->countCity($trip['id']);

                return $this->success('删除成功');
            }
        }
    }

    //ajax删除天
    public function deleteDay(){
        $post = $this->request->post();
        $schedule_id = $post['schedule_id'];
        $schedule = db("schedule")->where("id",$schedule_id)->field("id,groupid")->find();
        $trip = db('trip')->where('id', $schedule['groupid'])->find();

        $date = date("Y-m-d",$trip['start_go_time']);
        $days = db("schedule")->where("groupid",$schedule['groupid'])->count("id");
        $days = $days-1;
        if($days>0){
            db('trip')->where('id', $schedule['groupid'])->update(['days' =>$days]);
            if(!empty($schedule)){
                $active = db("active")->where('groupid',$schedule_id)->find();
                if(!empty($active)){
                    if(false == db("active")->where('groupid',$schedule_id)->delete()) {
                        return $this->error('删除失败');
                    }
                }
                if(false == db("schedule")->where('id',$schedule_id)->delete()) {
                    return $this->error('删除失败');
                } else {
                    //重新排序日期
                    $new_schedule = db("schedule")->where("groupid",$schedule['groupid'])->order("displayorder asc")->select();
                    $num = 1;
                    foreach ($new_schedule as $k=>$v) {
                        db('schedule')->where('id', $v['id'])->update(['time' =>$date,'displayorder'=>$num]);
                        $num++;
                        $date = date("Y-m-d",strtotime("+1 day",strtotime($date)));
                    }

                    //统计城市
                    $this->countCity($trip['id']);

                    return $this->success('删除成功');
                }
            }
        }else{
            return $this->error('至少要有一日行程！');
        }
    }

    //ajax拖拽修改排序
    public function changeDrag(){
        $post = $this->request->post();
        $type = $post['type'];// 1为day  2为poi
        if($type==1){//修改Day排序
            $tripid = $post['tripid'];
            $schedule_id_str = $post['days_str'];
            $schedule_id_Arr = explode(",",$schedule_id_str);
            $schedule_id_Arr = array_filter($schedule_id_Arr);
            $num = 1;

            $trip = db('trip')->where('id', $tripid)->field("start_go_time")->find();
            $date = date("Y-m-d",$trip['start_go_time']);

            foreach ($schedule_id_Arr as $k=>$v) {
                $schedule_id = $v;
                db('schedule')->where('id', $schedule_id)->update(['displayorder' =>$num,'time'=>$date]);
                $num++;
                $date = date("Y-m-d",strtotime("+1 day",strtotime($date)));
            }
            //统计城市 刷新城市地图
            $this->countCity($tripid);

            return $this->success('排序成功');
        }elseif($type==2){//修改poi排序
            $active_id = $post['active_id'];
            $schedule_id = $post['schedule_id'];
            $active_id_str = $post['actives_str'];
            $active_id_Arr = explode(",",$active_id_str);
            $active_id_Arr = array_filter($active_id_Arr);
            $num = 1;
            $trip = db("schedule")->field("groupid")->where("id",$schedule_id)->find();
            db('active')->where('id', $active_id)->update(['groupid' =>$schedule_id]);
            foreach ($active_id_Arr as $k=>$v) {
                db('active')->where('id',$v)->update(['displayorder' =>$num]);
                $num++;
            }
            //统计城市 刷新城市地图
            $this->countCity($trip['groupid']);
            return $this->success('排序成功');
        }else{
            return $this->error('排序失败');
        }
    }

    //获取可导入的行程列表
    public function getTripForImport(){
        $post = $this->request->post();
        $where = [];
        $qurey = "";
        if(!empty($post['title'])){
            $title = $post['title'];
            $where['id|name'] = ['like','%'.$title.'%'];
        }
        //查看是否为合作方账号
        if($this->isPartnerUser()){
            //$where['allow_everyone_import'] = 1;
            //只允许导入模板和自己公司组织下的定制
            $admin_id = Cookie::get('admin');
            $adminInfo = [];
            if(empty($admin)){
                $adminInfo = db('admin')->find($admin_id);
            }
            $adminIds = [];
            if(!empty($adminInfo) && !empty($adminInfo['company_id'])){
                $adminIds = db('admin')->where('company_id',$adminInfo['company_id'])->column('id');
            }
            if(!empty($adminIds)){
                $qurey = function ($qurey) use ($adminIds){
                    $qurey->where('is_template',1)->whereOr(['adminid'=>['in',$adminIds]]);
                };
            }else{
                $qurey = [];
                $qurey['is_template'] = 1;
            }
        }
        //查询产品
        $trip1 = db("trip")->where($where)->where($qurey)->field("id,use_type,name,days,people,include_city")->select();
        //查询定制
        $trip2 = db("product")->where($where)->field("id,use_type,name,days,people,include_city")->select();
        if($this->isPartnerUser()){
            $trip = $trip1;
        }else{
            $trip = array_merge($trip1,$trip2);
        }


        $res_trip = [];
        if(!empty($post['citys'])){
            $city_str = $post['citys'];
            $city_arr = explode(",",$city_str);
            $city_arr = array_filter($city_arr);
            foreach ($trip as $k=>$v) {
                $flag = 1;
                $include_city = $v['include_city'];
                if(!empty($include_city) && $include_city!==''){
                    $include_city_arr = explode(",",$include_city);
                    foreach ($city_arr as $city) {
                        if(!in_array($city,$include_city_arr)){
                            $flag = 0;
                            break;
                        }
                    }
                }else{
                    continue;
                }

                if($flag==1){
                    $res_trip[] = $v;
                }
            }
        }else{
            $res_trip = $trip;
        }

        return $res_trip;
    }

    //统计trip内城市
    public function countCity($trip_id){
        if(empty($trip_id) || $trip_id<=0){
            return false;
        }
        $cityArr = [];
        $include_city = "";
        $cityCounts = 0;
        $schedule = db("schedule")->where("groupid",$trip_id)->select();
        if(!empty($schedule)){
            $schedule_ids = array_column($schedule,"id");
            if(!empty($schedule_ids)){
                $cityid_arr = db("active a")
                    ->join("schedule s","s.id=a.groupid","left")
                    ->where(["a.groupid"=>['in',$schedule_ids]])
                    ->field("a.cityid")
                    ->order("s.displayorder asc,a.displayorder asc")//获取poi的正确顺序
                    ->select();
                if(!empty($cityid_arr)){
                    $cityArr = array_column($cityid_arr,"cityid");
                    $include_city = implode(",",$cityArr);

                    $cityUniqueArr = array_unique($cityArr);
                    $cityCounts = count($cityUniqueArr);
                }
            }
        }

        $tripInfo = db("trip")->find($trip_id);
        if($include_city!=$tripInfo['include_city']){
            $thumb_map_img = "";
            if(!empty($cityArr)){
                //获取所有城市的经纬度
                $cityLatLng = db("city")->field("id,lat,lng")->where(['id'=>['in',$cityArr]])->select();
                //如果所有城市都是一个城市，不需要生成地图图片
                if(count($cityLatLng)>1){
                    $map_city = [];
                    foreach ($cityArr as $key=>$value){
                        foreach ($cityLatLng as $k=>$v){
                            $last_latLng = end($map_city);
                            if($value==$v['id'] && $last_latLng !=$v && !empty($v['lat']) && !empty($v['lng'])){
                                $map_city[] = $v;
                            }
                        }
                    }
                    if(!empty($map_city)){
                        //$thumb_map_img = (new GoogleMap())->getGoogleMapImgByRoad($map_city,500,300);
                    }
                }
            }
            //更新包含城市和路线地图
            db("trip")->where("id",$trip_id)->update(['citys'=>$cityCounts,'include_city'=>$include_city,'thumb_map_img'=>$thumb_map_img]);
        }

        return true;
    }

    //脚本添加城市
    public function forCountCity(){
        $trip = db("trip")->field("id")->order("id desc")->select();
        foreach ($trip as $key=>$value) {
            $trip_id = $value['id'];
            $cityArr = [];
            $schedule = db("schedule")->where("groupid",$trip_id)->select();
            foreach ($schedule as $k=>$v) {
                $where['groupid']= $v['id'];
                $cityid_arr = db("active")
                    ->where($where)
                    ->field("poiid,cityid")
                    ->select();
                if(!empty($cityid_arr)){
                    foreach ($cityid_arr as $city) {
                        if(!empty($city['poiid']) && $city['poiid']>0){
                            if(!in_array($city['cityid'],$cityArr)){
                                $cityArr[] = $city['cityid'];
                            }
                        }
                    }
                }
            }

            $include_city = implode(",",$cityArr);
            $res = db("trip")->where("id",$trip_id)->update(['include_city'=>$include_city]);

            echo "<br>";
            echo $trip_id."：";
            var_dump($include_city);
            echo "-----";
            var_dump($res);
            echo "<br>";
        }

    }

    //更新每日行程中的地图
    public function updateEveryDayPOIMapImg()
    {
        $post = $this->request->post();
        $trip_id = isset($post['trip_id'])&&!empty($post['trip_id'])?$post['trip_id']:0;
        if(empty($trip_id)){
            return json(['code'=>-1,"msg"=>'请求错误']);
        }
        $schedule = db("schedule")->where("groupid",$trip_id)->select();
        if(empty($schedule)){
            return json(['code'=>-1,"msg"=>'请先添加日程']);
        }else{
            $schedule_ids = array_column($schedule,"id");
            $active = db("active a")
                ->field("a.id,a.groupid,a.poiid,p.lat,p.lng")
                ->join("poi p","p.id=a.poiid","left")
                ->where(['a.groupid'=>['in',$schedule_ids]])
                ->order("a.displayorder asc")//获取poi的正确顺序
                ->select();
            foreach ($schedule as $key=>$value){
                $schedule[$key]['poilist'] = [];
                foreach ($active as $k=>$v){
                    //未选择poi需要过滤
                    if($value['id']==$v['groupid'] && !empty($v['poiid'])){
                        $schedule[$key]['poilist'][] = $v;
                    }
                }
            }
            db::startTrans();
            try{
                //更新每个日程的线路图
                foreach ($schedule as $key=>$value){
                    $thumb_map_img = "";
                    if(!empty($value['poilist'])){
                        $thumb_map_img = (new GoogleMap())->getGoogleMapImgByRoad($value['poilist'],500,300);
                    }
                    db("schedule")->where("id",$value['id'])->update(['thumb_map_img'=>$thumb_map_img]);
                }
                db::commit();
                return json(['code'=>200,'msg'=>"更新成功"]);
            }catch (Exception $e){
                db::rollback();
                return json(['code'=>-1,'msg'=>"更新失败"]);
            }
        }
    }

    //更新每日行程中的地图是否显示
    public function changeShowScheduleMapImg()
    {
        $post = $this->request->post();
        $trip_id = isset($post['trip_id'])&&!empty($post['trip_id'])?$post['trip_id']:0;
        if(empty($trip_id)){
            return json(['code'=>-1,"msg"=>'请求错误']);
        }
        $is_show = isset($post['is_show'])&&$post['is_show']==1?1:0;
        $res = db("trip")->where("id",$trip_id)->update(['show_day_map'=>$is_show]);

        if($res!==false){
            return json(['code'=>200,"msg"=>'更新成功']);
        }else{
            return json(['code'=>-1,"msg"=>'更新失败']);
        }
    }

    //更新行程中的总地图是否显示
    public function changeShowCityMapImg()
    {
        $post = $this->request->post();
        $trip_id = isset($post['trip_id'])&&!empty($post['trip_id'])?$post['trip_id']:0;
        if(empty($trip_id)){
            return json(['code'=>-1,"msg"=>'请求错误']);
        }
        $is_show = isset($post['is_show'])&&$post['is_show']==1?1:0;
        $res = db("trip")->where("id",$trip_id)->update(['show_city_map'=>$is_show]);
        if($res!==false){
            return json(['code'=>200,"msg"=>'更新成功']);
        }else{
            return json(['code'=>-1,"msg"=>'更新失败']);
        }
    }

    //快速定制推荐POI列表
    public function getRecommendPoiList()
    {
        $post = $this->request->post();
        $poi_id = isset($post['poi_id'])&&!empty($post['poi_id'])?$post['poi_id']:0;
        if(empty($poi_id)){
            return json(['code'=>-1,"msg"=>'请求错误']);
        }
        $model = new PModel();
        $poilist = $model->getNearbyPOI($poi_id,50000);
        //获取城市名称
        if(!empty($poilist)){
            $cityids = array_column($poilist,"groupid");
            $cityList = db("city")->where(['id'=>['in',$cityids]])->select();
            foreach ($poilist as $key=>$value){
                $poilist[$key]['cityId'] = 0;
                $poilist[$key]['cityName'] = '';
                foreach ($cityList as $k=>$v){
                    if($value['groupid']==$v['id']){
                        $poilist[$key]['cityName'] = $v['name'];
                        $poilist[$key]['cityId'] = $v['id'];
                    }
                }
            }
        }
        return json(['code'=>200,'msg'=>"获取列表成功","data"=>$poilist]);
    }

    //查看每日地图
    public function getDayMap()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $ajax = $this->request->has('ajax') ? $this->request->param('ajax', 0, 'intval') : 0;
        if($id>0){
            $schedule = db("schedule")->find($id);
            $hasLine = false;
            $map['start_poi'] = [];
            $map['end_poi'] = [];
            $map['middle_poi'] = [];
            if(!empty($schedule)){
                $active = db("active a")
                    ->field("a.id,a.activeType,a.title,p.name,p.eng_name,p.lat,p.lng,a.airport_lat,a.airport_lng")
                    ->join("poi p","p.id=a.poiid",'left')
                    ->where(['a.groupid'=>$id])
                    ->order("a.displayorder asc")
                    ->select();
                //将经纬度转换成float类型
                foreach ($active as $key=>$value){
                    if(in_array($value['activeType'],[1,4,15,16,17,18,19])){
                        $value['lat'] = floatval($value['lat']);
                        $value['lng'] = floatval($value['lng']);
                    }elseif(in_array($value['activeType'],[2,3])){
                        $value['lat'] = floatval($value['airport_lat']);
                        $value['lng'] = floatval($value['airport_lng']);
                        $active[$key]['name'] = $value['title'];
                    }else{
                        $value['lat'] = 0;
                        $value['lat'] = 0;
                    }

                    if(empty($value['lat']) || empty($value['lng'])){
                        unset($active[$key]);
                    }else{
                        $active[$key]['lat'] = floatval($value['lat']);
                        $active[$key]['lng'] = floatval($value['lng']);
                    }
                }
                if(count($active)>=2){
                    $hasLine = true;
                    $map['start_poi'] = array_shift($active);
                    $map['end_poi'] = array_pop($active);
                    $map['middle_poi'] = $active;
                }
            }
        }
        if(!empty($ajax)){
            return json(['code'=>200,'msg'=>'获取成功','data'=>['map'=>$map,'hasLine'=>$hasLine]]);exit;
        }else{
            $this->assign("map",$map);
            $this->assign("hasLine",$hasLine);
            return $this->fetch();
        }
    }

    //配置页面
    public function tripConfig()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $trip = db("trip")->find($id);
        if(empty($trip)){
            return $this->error('行程信息有误');
        }
        if(request()->isPost()){
            $post = request()->post();
            if(!empty($post)){
                $post_data = [];
                $config_arr = ['showmobile','showticket','showopen_time','showticket_url','showeng_introduce','showdescription','showprice','showthumb','showsource','showaddress','showgrade','show_day_map','show_city_map','showcontent','showpoicontent','showcareful','showback','showintroduction','showpricedetail','allow_everyone_import'];
                foreach ($config_arr as $value){
                    $post_data[$value] = 0;
                }
                foreach ($post as $key=>$value){
                    if(in_array($key,$config_arr) && $value=='on'){
                        $post_data[$key] = 1;
                    }
                }
                $post_data['introduction'] = $post['introduction'];
                $post_data['custom_made_description'] = $post['custom_made_description'];
                $post_data['price'] = $post['price'];
                $post_data['priceno'] = $post['priceno'];
                $post_data['careful'] = $post['careful'];
                $post_data['back'] = $post['back'];
                if(!empty($post['trip_banner'])){
                    $post_data['trip_banner'] = $post['trip_banner'];
                }
                $res = db("trip")->where(['id'=>$id])->update($post_data);
                if($res!==false){
                    return $this->success("修改成功");
                }else{
                    return $this->error("修改失败");
                }
            }else{
                return $this->error("修改失败");
            }
        }
        $this->assign('trip',$trip);
        return $this->fetch();
    }

    //获取机场
    public function kbxGetAirport($city_id)
    {
        $data = [];
        if(isset($city_id) && $city_id>0){
            $city = db("city")->where("id",$city_id)->field("kbx_id")->find();
            $kbxToken = new KbxToken();
            $url = $kbxToken->url.'/cities/'.$city['kbx_id'].'/airports';
            $token = 'Bearer ' . $kbxToken->kbxToken();
            $res = $kbxToken->get_data($url, $token);
            $data = $kbxToken->object_array($res);
        }

        return $data;
    }

    //计算景点距离
    public function getDistance($lat1, $lng1, $lat2, $lng2){
        $earthRadius = 6367000; //approximate radius of earth in meters
        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;
        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;
        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        return round($calculatedDistance);
    }

    //获取active两节点间距离
    public function getActiveDistance($num,$active){
        if($num<(count($active)-1)){
            $poi1 = [];
            $poi2 = [];
            $typeid1 = $active[$num]['activeType'];
            $typeid2 = $active[$num+1]['activeType'];

            if($typeid1==1 || $typeid1==4){// 1=POI  4=酒店
                $poiData= Db::name('poi')->where('id',$active[$num]['poiid'])->field('lat,lng')->find();
                $poi1['lat'] = $poiData['lat'];
                $poi1['lng'] = $poiData['lng'];
            }elseif($typeid1==2 || $typeid1=3){// 2=接机  3=送机
                $poi1['lat'] = $active[$num]['airport_lat'];
                $poi1['lng'] = $active[$num]['airport_lng'];
            }

            if($typeid2==1 || $typeid2==4){// 1=POI  4=酒店
                $poiData= Db::name('poi')->where('id',$active[$num+1]['poiid'])->field('lat,lng')->find();
                $poi2['lat'] = $poiData['lat'];
                $poi2['lng'] = $poiData['lng'];
            }elseif($typeid2==2 || $typeid2=3){// 2=接机  3=送机
                $poi2['lat'] = $active[$num+1]['airport_lat'];
                $poi2['lng'] = $active[$num+1]['airport_lng'];
            }

            if(isset($poi1['lat'])&&isset($poi1['lng'])&&isset($poi2['lat'])&&isset($poi2['lng'])){
                $limit = $this->getDistance($poi1['lat'],$poi1['lng'],$poi2['lat'],$poi2['lng']);
            }else{
                $limit=0;
            }

            return round($limit/1000,1);
        }else{
            return 0;
        }
    }

    //ajax  获取节点前后  一共三个节点的距离
    public function getPointDistance(){
        if(request()->isPost()) {
            $post = request()->post();
            $groupid = $post['groupid'] ?? '';
            $active_id = $post['active_id'] ?? '';
            if(empty($groupid) || empty($active_id)){
                return $this->error('无法获取距离');
            }

            $active = db("active")
                ->where("groupid",$groupid)
                ->order("displayorder asc")
                ->field("id,poiid,activeType,airport_lat,airport_lng")
                ->select();

            //获取距离
            $disArr = [];
            foreach ($active as $k=>$v) {
                if($v['id']==$active_id){
                    $disArr[] = [
                        'id'=>$active[$k]['id'],
                        'distance'=>$this->getActiveDistance($k,$active)
                    ];

                    if($k==0){
                        if(count($active)>1){
                            $disArr[] = [
                                'id'=>$active[$k+1]['id'],
                                'distance'=>$this->getActiveDistance($k+1,$active)
                            ];
                        }
                    }elseif($k==count($active)-1){
                        $disArr[] = [
                            'id'=>$active[$k-1]['id'],
                            'distance'=>$this->getActiveDistance($k-1,$active)
                        ];
                    }else{
                        $disArr[] = [
                            'id'=>$active[$k-1]['id'],
                            'distance'=>$this->getActiveDistance($k-1,$active)
                        ];
                        $disArr[] = [
                            'id'=>$active[$k+1]['id'],
                            'distance'=>$this->getActiveDistance($k+1,$active)
                        ];
                    }
                }
            }

            return $disArr;
        }else{
            return $this->error('获取距离失败');
        }
    }

    //更新节点详细数据
    public function updateActiveInfo(){
        $post = $this->request->post();
        $active_id = isset($post['active_id'])&&!empty($post['active_id'])?$post['active_id']:0;
        $active = db("active")->find($active_id);
        if(empty($active)){
            return json(['code'=>-1,"msg"=>'请求错误']);
        }
        $activeModel = new activeModel();
        if(isset($post['title']) && $active['activeType']==6){
            $post['poiname'] = $post['title'];
            $post['poiImg'] = '';
        }
        if(!empty($_POST['content'])) $post['content'] = $_POST['content'];
        if(!empty($_POST['poi_content'])) $post['poi_content'] = $_POST['poi_content'];
        if(false == $activeModel->allowField(true)->save($post,["id"=>$active_id])) {
            return $this->error('保存失败');
        } else {
            Cache::rm('trip_preview_thumbimg_'.$active_id);
            return $this->success('保存成功','');
        }
    }

    //获取active详情用于修改active
    public function getActiveInfo(){
        $post = $this->request->post();
        $active_id = isset($post['active_id'])&&!empty($post['active_id'])?$post['active_id']:0;
        $active = db("active")->find($active_id);

        if(empty($active)){
            return json(['code'=>-1,"msg"=>'请求错误']);
        }else{
            $poi = db("poi")->where("id",$active['poiid'])->field("introduce,thumb")->find();
            //当POI简介不存在时，去POI表中获取补录
            if(empty($active['poi_content'])){
                $introduce = $poi['introduce'];
                if(!empty($introduce)){
                    $activeModel = new activeModel();
                    $activeModel->allowField(true)->save(['poi_content'=>$introduce],['id'=>$active_id]);
                    $active['poi_content'] = $introduce;
                }
            }

            $poiImg_arr = array_values(array_filter(explode(",",$active['poiImg'])));
            $other_images_arr = array_values(array_filter(explode(",",$active['other_images'])));
            // 默认不推荐用户poi图片 2019-06-06
            //$thumb = array_values(array_filter(explode(",",$poi['thumb'])));
            //$poiImg_arr = array_merge($poiImg_arr,$thumb);
            $p_arr = [];
            $o_arr = [];
//            $p_arr[] = array_shift($poiImg_arr);
//            $p_arr[] = array_shift($poiImg_arr);
//            $o_arr[] = array_shift($other_images_arr);
//            $o_arr[] = array_shift($other_images_arr);

            $p_arr = $poiImg_arr;
            $o_arr = $other_images_arr;

            $active['poiImg_arr'] = array_filter($p_arr);
            $active['other_images_arr'] = array_filter($o_arr);
            return json(['code'=>200,"msg"=>'获取成功','data'=>$active]);
        }
    }

    //定制页面导入行程
    public function tripimport()
    {
        if($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post();

            //导入行程id串
            if(!empty($post['tripids'])){
                $tripids = $post['tripids'];
                $tripsArr = explode(",",$tripids);
            }else{
                $tripsArr = [];
            }
            if(!empty($post['productids'])){
                $productids = $post['productids'];
                $productsArr = explode(",",$productids);
            }else{
                $productsArr = [];
            }
            if(empty($tripsArr) && empty($productsArr)){
                return $this->error("至少要选择一个行程导入！");
            }

            if(empty($post['trip_id'])){
                return $this->error("导入失败！");
            }else{
                $tripInfo = db("trip")->find($post['trip_id']);
                if(empty($tripInfo)){
                    return $this->error("行程有误！");
                }
            }
            $tripid = $post['trip_id'];
            $scheduleList = db("schedule")->field("id,time,displayorder")->where(['groupid'=>$tripInfo['id']])->order("displayorder asc")->select();
            $days = count($scheduleList);
            $schedulenum = $days+1;
            $start_date = date("Y-m-d",strtotime("+".$days." day",$tripInfo['start_go_time']));
            $res = $this->importOldTripByTripIds($tripsArr,$productsArr,$tripid,$start_date,$days,$schedulenum);
            if($res){
                return $this->success('导入成功',"",$tripid);
            }else{
                return $this->error('导入失败');
            }
        }else{
            $where['type'] = "CITY";
            $where['deleted'] = 0;

            $city = db("city")->where($where)->field("id,name")->select();

            $cityJson = json_encode($city,JSON_UNESCAPED_UNICODE);

            $this->assign('city',$city);
            $this->assign('cityJson',$cityJson);

            return $this->fetch();
        }
    }

    //导入实现
    private function importOldTripByTripIds($tripsArr,$productsArr,$tripid,$start_date,$days=0,$schedulenum=1)
    {
        //查看是否为合作方账号
        $where_partner = [];
        if($this->isPartnerUser()){
            $where_partner['activeType'] = ["not in",[2,3,4,5]];
        }

        $model = new tripModel();
        //复制导入行程
        Db::startTrans(); //启动事务
        try {
            $date = $start_date;
            $nowtime = time();
            if(!empty($tripsArr)){
                foreach ($tripsArr as $key=>$value){
                    $getschedule= Db::name("schedule")->where(['groupid' => $value])->order("displayorder asc")->select();
                    $days+=count($getschedule);
                    foreach ($getschedule as $k=>$v) {
                        $tempnowscheduleid = $v['id'];
                        unset($v['id']);
                        $v['time'] = $date;
                        $v['groupid'] = $tripid;
                        $v['displayorder'] = $schedulenum;
                        $schedulenum+=1;
                        $v['create_time'] = $nowtime;
                        $v['update_time'] = $nowtime;

                        //插入日程数据
                        $scheduleModel = new scheduleModel();
                        $scheduleModel->allowField(true)->save($v);
                        $newscheduleid=$scheduleModel->getLastInsID();
                        $date = date("Y-m-d",strtotime("+1 day",strtotime($date)));

                        if ($newscheduleid) {
                            $getactive= Db::name("active")
                                ->where(['groupid' => $tempnowscheduleid])
                                ->where($where_partner)
                                ->order("displayorder asc")
                                ->select();
                            foreach ($getactive as $m=>$n) {
                                //typeid弃用   by Suley  2019-08-21
                                if(!empty($n['poiid']) && is_numeric($n['poiid'])==true){
                                    $poi = db("poi")->where("id",$n['poiid'])->find();
                                    if($poi['deleted']==1){
                                        continue;
                                    }
                                    $n['poiname'] = !empty($poi['name'])?$poi['name']:$n['poiname'];
                                }
                                $n['other_images'] = '';
                                $n['showthumb'] = 1;
                                $n['groupid'] = $newscheduleid;
                                $n['create_time'] = $nowtime;
                                $n['update_time'] = $nowtime;
                                $n['time'] = "";

                                //插入日程数据
                                unset($n['id']);
                                $activeModel = new activeModel();
                                $activeModel->allowField(true)->save($n);
                            }
                        }
                    }
                }
            }
            if(!empty($productsArr)){
                foreach ($productsArr as $key=>$value){
                    $getschedule= Db::name("pschedule")->where(['groupid' => $value])->order("displayorder asc")->select();
                    $days+=count($getschedule);
                    foreach ($getschedule as $k=>$v) {
                        $tempnowscheduleid = $v['id'];
                        unset($v['id']);
                        $v['time'] = $date;
                        $v['groupid'] = $tripid;
                        $v['displayorder'] = $schedulenum;
                        $schedulenum+=1;
                        $v['create_time'] = $nowtime;
                        $v['update_time'] = $nowtime;

                        //插入日程数据
                        $scheduleModel = new scheduleModel();
                        $scheduleModel->allowField(true)->save($v);
                        $newscheduleid=$scheduleModel->getLastInsID();
                        $date = date("Y-m-d",strtotime("+1 day",strtotime($date)));
                        if ($newscheduleid) {
                            $getactive= Db::name("pactive")
                                ->where(['groupid' => $tempnowscheduleid])
                                ->where($where_partner)
                                ->order("displayorder asc")
                                ->select();
                            foreach ($getactive as $m=>$n) {
                                //typeid弃用   by Suley  2019-08-21
                                if(!empty($n['poiid']) && is_numeric($n['poiid'])==true){
                                    $poi = db("poi")->where("id",$n['poiid'])->find();
                                    if($poi['deleted']==1){
                                        continue;
                                    }
                                    $n['poiname'] = !empty($poi['name'])?$poi['name']:$n['poiname'];
                                }
                                $n['other_images'] = '';
                                $n['showthumb'] = 1;
                                $n['groupid'] = $newscheduleid;
                                $n['create_time'] = $nowtime;
                                $n['update_time'] = $nowtime;
                                $n['time'] = "";
                                //插入日程数据
                                unset($n['id']);
                                unset($n['own_fee']);
                                $activeModel = new activeModel();
                                $activeModel->allowField(true)->save($n);
                            }
                        }
                    }
                }
            }
            $update_data['days']=$days;
            unset($update_data['is_template']);
            $model->allowField(true)->save($update_data,['id'=>$tripid]);

            $this->countCity($tripid);

            Db::commit(); //提交事务
            return true;
        } catch (Exception $e) {
            Db::rollback(); //回滚事务
            return false;
        }
    }

    //重排日期
    public function revertDay($tripid){
        $trip = db('trip')->where('id', $tripid)->find();
        $date = date("Y-m-d",$trip['start_go_time']);
        $days = $trip['days'];
        if($days>0){
            //重新排序日期
            $scheduleArr = db("schedule")->where("groupid",$tripid)->order("displayorder asc")->select();
            $num = 1;
            foreach ($scheduleArr as $k=>$v) {
                db('schedule')->where('id', $v['id'])->update(['time' =>$date,'displayorder'=>$num]);
                $num++;
                $date = date("Y-m-d",strtotime("+1 day",strtotime($date)));
            }
            return true;
        }else{
            return false;
        }
    }


    public function traffic()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $trip = db("trip")->find($id);
        if(empty($trip)){
            return $this->error('行程信息有误');
        }
        $schedules = Db::name('schedule')->field("id,displayorder,time,groupid")->where('groupid',$id)->order('displayorder')->select();
        $schedule_ids = array_column($schedules,"id");
        if(!empty($schedule_ids)) {
            $activeList = db('active a')
                ->join("city c", "c.id=a.cityid", 'left')
                ->join("poi p", "p.id=a.poiid", 'left')
                ->field("a.id,a.displayorder,a.title,a.poiname,a.groupid")
                ->where(['a.groupid' => ['in', $schedule_ids]])
                ->order('a.groupid,a.displayorder')
                ->select();
        }else{
            return $this->error('请先添加节点');
        }
        $trip_index_arr = [];
        foreach ($schedules as $key=>$value){
            $schedules[$key]['label'] = "第".$value['displayorder']."天";
            $schedules[$key]['children'] = [];
            foreach ($activeList as $k=>$v){
                if($v['groupid']==$value['id']){
                    $v['label'] = empty($v['poiname'])?$v['title']:$v['poiname'];
                    $schedules[$key]['children'][] = $v;
                    //计算节点个数
                    $trip_index_arr[] = $key.'-'.(count($schedules[$key]['children'])-1);
                }
            }
        }
        $transport_json = json_decode($trip['transport_json'],true);
        $transport_json = !empty($transport_json)?$transport_json:[];
        $transportList = [];
        if(!empty($transport_json)){
            $transport_arr = $this->deconstructTransJson($transport_json,$trip_index_arr);
            foreach ($schedules as $key=>$value){
                foreach ($value['children'] as $child_key=>$child_value){
                    if(in_array($key.'-'.$child_key,$transport_arr)){
                        $schedules[$key]['disabled'] = true;
                        $schedules[$key]['children'][$child_key]['disabled'] = true;
                    }
                }
            }
        }else{
            $transport_arr = [];
        }


//        var_dump($schedules);exit;
        $this->assign('trip',$trip);
        $this->assign('transport',$this->getTransportTitle());
        $this->assign("schedules",$schedules);
        //展示交通列表
        $transList = $this->getDaysByTransJson($transport_json,$schedules);
        $this->assign("transList",$transList);
        return $this->fetch();
    }

    //获取交通类型 （用于订单系统核价）
    public function getTransportType($type_id)
    {
        $data =  [
            "1"=>"Transport_Vehicle_FromAirport",
            "2"=>"Transport_Vehicle_ToAirport",
            "8"=>"Transport_Vehicle_ShortDistance",
            "3"=>"Transport_Vehicle_HalfDay",
            "4"=>"Transport_Vehicle_OneDay",
            "5"=>"Transport_Vehicle_Around",
            "6"=>"Transport_Vehicle_LongTrip",
            "7"=>"self",
        ];

        if(!empty($type_id)){
            return $data[$type_id];
        }else{
            return $data;
        }
    }

    //获取交通类型 用于前端展示
    public function getTransportTitle($type_id = 0)
    {
        $data =  [
            "1"=>"接机",
            "2"=>"送机",
            "8"=>"单程接送",
            "3"=>"市区半日包车",
            "4"=>"市区一日包车",
            "5"=>"周边一日包车",
            "6"=>"长途包车",
            "7"=>"自驾",
        ];

        if(!empty($type_id)){
            return $data[$type_id];
        }else{
            return $data;
        }
    }

    //批量创建交通
    public function createMoreTransport()
    {
        $post = request()->post();
        if(!empty($post)){
            $trip_id = isset($post['trip_id'])?$post['trip_id']:0;
            $index = isset($post['index'])?$post['index']:"";
            $trans_type = isset($post['trans_type'])?$post['trans_type']:0;
            $days = isset($post['days'])?$post['days']:[];
            $items = isset($post['items'])?$post['items']:[];
            $trip = db("trip")->find($trip_id);
            if(empty($trip)){
                $this->error("行程信息有误");exit;
            }
            if(!in_array($trans_type,[1,2,3,4,5,6,8]) || empty($days) || empty($items)){
                $this->error("参数信息有误");exit;
            }
            $transItem = [];
            //修改任何类型随意设置节点 2019 08 06
                reset($items);
                $start = current($items);
                $end = end($items);
                $transItem[] = [
                    'type'=>$trans_type,
                    'start'=>$start,
                    'end'=>$end
                ];
            //对项目进行排序
            $_json = json_decode($trip['section_trans_json'],true);
            $_json[$index] = $_json[$index]??[];
            $_json[$index] = array_merge($_json[$index],$transItem);
            $trans_json = json_encode($_json);
            $res = db("trip")->where(['id'=>$trip_id])->update(['section_trans_json'=>$trans_json]);
            if($res!==false){
                $this->success("保存成功","",$transItem);
            }else{
                $this->error("保存失败");
            }
        }else{
            $this->error("请求错误");exit;
        }
    }

    //解构json数据
    public function deconstructTransJson($json_arr,$trip_arr){
        $data = [];
        if(empty($json_arr)){
            return [];
        }else{
            foreach ($json_arr as $key=>$value){
                $s_index = array_search($value['start'],$trip_arr);
                $e_index = array_search($value['end'],$trip_arr);
                if($s_index<$e_index){
                    $section_data = array_slice($trip_arr,$s_index,$e_index-$s_index+1);
                    $data = array_merge($data,$section_data);
                }else{
                    $data[] = $trip_arr[$s_index];
                }
            }
        }
        return $data;
    }

    //获取天数的标签
    public function getDaysByTransJson($json_arr,$actives)
    {
        if(empty($json_arr)){
            return [];
        }else{
            foreach ($json_arr as $key=>$value){
                $s_day = explode("-",$value['start'])[0];
                $e_day = explode("-",$value['end'])[0];
                $s_poi = explode("-",$value['start'])[1];
                $e_poi = explode("-",$value['end'])[1];
                $json_arr[$key]['s_day'] = intval($s_day);
                $json_arr[$key]['e_day'] = intval($e_day);
                $s_label = $actives[$s_day]['children'][$s_poi]['label'];
                $e_label = $actives[$e_day]['children'][$e_poi]['label'];
                if($s_label==$e_label){
                    $json_arr[$key]['s_poiname'] = '/';
                }else{
                    $json_arr[$key]['s_poiname'] = $s_label;
                }
                $json_arr[$key]['e_poiname'] = $e_label ;
                if($s_day==$e_day){
                    $json_arr[$key]['day_title'] ='第'.($s_day+1).'天';
                }else{
                    $json_arr[$key]['day_title'] ='第'.($s_day+1).'天至第'.($e_day+1).'天';
                }

                $json_arr[$key]['type_title'] =$this->getTransportTitle($value['type']);
            }
        }
        $sday_arr = array_column($json_arr,"s_day");
        $eday_arr = array_column($json_arr,"e_day");
        array_multisort($sday_arr,SORT_ASC,$eday_arr,SORT_ASC,$json_arr);
        return $json_arr;
    }

    //修改每日交通类型
    public function updTransportType()
    {
        $post = request()->post();
        $schedule_id = isset($post['schedule_id'])?$post['schedule_id']:0;
        $upd_type = isset($post['upd_type'])?$post['upd_type']:"update";
        $schedule = db("schedule")->find($schedule_id);
        if(empty($schedule)){
            $this->error("日程错误");exit;
        }else{
            $res= db("schedule")->where(['id'=>$schedule_id])->update(['transport_typeids'=>$post{'day_type'}]);
            if($res){
                if($upd_type=='delete'){
                    $this->success("删除成功");
                }else{
                    $this->success("修改成功");
                }
            }else{
                $this->error("修改失败");
            }
        }
    }

    //核价表格
    public function priceTable($trip_id=0){
        if($trip_id>0){
            $dayData = [];
            $num = 1;
            $weekArray=array("日","一","二","三","四","五","六");

            $hotelFlag = 0;
            $hotelNum = 1;
            $hotelShow = 1;
            $drive_num = 1;//判断连续几天
            $schedule = db("schedule")->where("groupid",$trip_id)->order("displayorder asc")->select();
            if(!empty($schedule)){
                foreach ($schedule as $key=>$value) {
                    $day = [];
                    $active = db("active")->where("groupid",$value['id'])->order("displayorder asc")->select();

                    $day['day'] = "第".$num."天";
                    $day['time'] = $value['time'];
                    $day['title'] = $value['title'];
                    $day['transport_typeids'] = $value['transport_typeids'];
                    $day['week'] = "周".$weekArray[date("w",strtotime($value['time']))];

                    $cityArr = [];
                    $airportArr = [];
                    $activeText = '';
                    $hotel = '';
                    $hotel_id = '';
                    $hotel_time = [];
                    $hotel_key = 0;
                    if(!empty($active)){
                        foreach ($active as $k=>$v) {
                            if(!empty($v['cityname']) && $v['cityname']!=='' && !in_array($v['cityname'],$cityArr)){
                                $cityArr[] = $v['cityname'];
                            }

                            $textTitle = '';
                            if($v['activeType']==1){
                                $textTitle = "景点";
                            }elseif($v['activeType']==2){//接机
                                $airportArr[] = [
                                    'id'=>$v['poiid'],
                                    'text'=>"接机：".$v['poiname'],
                                    'typeText'=>'接机',
                                    'flight'=>$v['flight'],
                                ];
                                $textTitle = "接机";
                            }elseif($v['activeType']==3){//送机
                                $airportArr[] = [
                                    'id'=>$v['poiid'],
                                    'text'=>"送机：".$v['poiname'],
                                    'typeText'=>'送机',
                                    'flight'=>$v['flight'],
                                ];
                                $textTitle = "送机";
                            }elseif($v['activeType']==4){//酒店
                                $hotel = $v['poiname'];
                                $hotel_id = $v['poiid'];
                                $hotel_key = $k;
                                if(!in_array($value['time'],$hotel_time)){
                                    $hotel_time[] = $value['time'];
                                }
                                $textTitle = "酒店";
                            }elseif($v['activeType']==5){//特色体验
                                $textTitle = "特色体验";
                            }elseif($v['activeType']==6){//其他
                                $textTitle = "其他";
                            }

                            $textTitle = $textTitle." - ".$v['poiname'];

                            if(!empty($v['time']) && $v['time']!==0 && $v['time']!==''){
                                $textTitle = $v['time']." - ".$textTitle;
                            }

                            $activeText .= $textTitle."<br>";
                        }
                    }

                    $citys = implode(" - ",$cityArr);
                    $day['citys'] = $citys;

                    //合并相邻日期相同酒店
                    if($hotel_id>0 && $hotel_key>0){
                        if($hotelFlag==$hotel_id){
                            $dayData[$key-$hotelNum]['hotel_num'] = $hotelNum+1;
                            $dayData[$key-$hotelNum]['alldayhotel'] .= ",".$value['id'];
                            $dayData[$key-$hotelNum]['hotel_time'][] = $value['time'];
                            $hotelNum++;
                            $hotelShow = 0;
                        }else{
                            $hotelNum = 1;
                            $hotelShow = 1;
                            $dayData[$key]['alldayhotel'] = $value['id'];
                        }
                        $hotelFlag = $hotel_id;
                    }else{
                        $hotel_id = 0;
                        $hotelFlag = 0;
                        $hotelNum = 0;
                        $day['alldayhotel'] = '';
                    }

                    //判断当天是否存在自驾
                    if(!empty($value['transport_typeids'])){
                        $trifficArr = explode(",",$value['transport_typeids']);
                        if(in_array("7",$trifficArr)){//存在自驾
                            if(isset($dayData[$key-1]['drive_flag']) && $dayData[$key-1]['drive_flag']==1){
                                $dayData[$key-$drive_num]['alldaydrive'] .= ",".$value['id'];
                                $dayData[$key-$drive_num]['drive_num'] = $drive_num+1;
                                $dayData[$key-$drive_num]['drive_time'][] = $value['time'];
                                $drive_num++;
                                $day['drive_num'] = 0;
                            }else{
                                $drive_num = 1;
                                $day['drive_num'] = 1;
                                $day['drive_time'][] = $value['time'];
                                $day['alldaydrive'] = $value['id'];
                            }
                            $day['drive_flag'] = 1;
                        }else{
                            $drive_num = 1;
                            $day['drive_flag'] = 0;
                            $day['drive_num'] = 0;
                            $day['alldaydrive'] = $value['id'];
                        }
                    }else{
                        $drive_num = 1;
                        $day['drive_num'] = 0;
                        $day['alldaydrive'] = '';
                        $day['drive_flag'] = 0;
                    }

                    $day['id'] = $value['id'];
                    $day['airport'] = $airportArr;
                    $day['hotel_id'] = $hotel_id;
                    $day['hotel_num'] = $hotelNum;
                    $day['hotel_time'] = $hotel_time;
                    $day['hotel_show'] = $hotelShow;
                    $day['hotel'] = $hotel;
                    $day['activeText'] = $activeText;
                    $day['alldayhotel'] = $value['id'];

                    $dayData[$key] = $day;
                    $num++;
                }
            }

            return $dayData;
        }else{
            return [];
        }
    }

    //交通核价接口封装
    //data是封装有active的schedule列表
    public function orderTransportApiData($id=604)
    {
        $trip = Db::name('trip')->where('id',$id)->find();
        //车型 默认是5座车 目前20座以上没有数据
        $carType = isset($trip['carType']) ? $trip['carType'] : 1;

        //$poiType = [1,4];//规定activeType去寻址poi
        //$airportType = [2,3];//规定activeType去寻址机场

        $resArr = [];
        $schedule = Db::name('schedule')->where('groupid',$id)->order('displayorder')->select();

        if(!empty($schedule)){
            foreach ($schedule as $s_key=>$s_value){
                if(empty($s_value['transport_typeids'])){
                    $activities = [];
                }else{
                    $activities = [];
                    $active = Db::name('active')
                        ->alias('a')
                        ->join('city c','a.cityid=c.id','left')
                        ->join('poi p','a.poiid=p.id','left')
                        ->where('a.groupid',$s_value['id'])
                        ->field("a.*,c.kbx_id as cityId,c.lat,c.lng,p.lat as poi_lat,p.lng as poi_lng")
                        ->order('a.displayorder')->select();
                    if(empty($active)){
                        continue;
                    }
                    $trans_type_arr = explode(',',$s_value['transport_typeids']);
                    //sort($trans_type_arr);
                    $airportActive = [];
                    $airportActiveIndex = 0;

                    foreach ($trans_type_arr as $t_v){
                        $from = [];
                        $to = [];
                        $pois = [];
                        if($t_v==1){//交通 接机
                            foreach ($active as $a_k=>$a_v){
                                if($a_v['activeType']==2){//接机类型
                                    $airportActive = $a_v;
                                    $airportActiveIndex = $a_k;
                                    unset($active[$a_k]);
                                    break;
                                }
                            }
                            if(empty($airportActive)){
                                continue;
                            }
                            $from = [
                                'cityid'=>$airportActive['cityId'],
                                'placeId'=>$airportActive['poiid'],
                                'location'=>[
                                    'lat'=>$airportActive['airport_lat'],
                                    'lng'=>$airportActive['airport_lng'],
                                ],
                            ];
                            if(isset($active[$a_k+1]) && !empty($active[$a_k+1]['lat']) && !empty($active[$a_k+1]['lng'])){
                                $to = [
                                    'cityid'=>$airportActive['cityId'],
                                    'placeId'=>$airportActive['poiid'],
                                    'location'=>[
                                        'lat'=>$active[$a_k+1]['poi_lat'],
                                        'lng'=>$active[$a_k+1]['poi_lng'],
                                    ],
                                ];
                            }else{
                                $to = $from;
                            }
                        }elseif($t_v==2){//交通 送机
//                            $active = array_reverse($active);
                            foreach ($active as $a_k=>$a_v){
                                if($a_v['activeType']==3){//送机类型
                                    $airportActive = $a_v;
                                    $airportActiveIndex = $a_k;
                                    unset($active[$a_k]);
                                    break;
                                }
                            }
                            if(empty($airportActive)){
                                //还原数组
//                                $active = array_reverse($active);
                                continue;
                            }
                            $to = [
                                'cityid'=>$airportActive['cityId'],
                                'placeId'=>$airportActive['poiid'],
                                'location'=>[
                                    'lat'=>$airportActive['airport_lat'],
                                    'lng'=>$airportActive['airport_lng'],
                                ],
                            ];
                            if(isset($active[$a_k+1]) && !empty($active[$a_k+1]['lat']) && !empty($active[$a_k+1]['lng'])){
                                $from = [
                                    'cityid'=>$airportActive['cityId'],
                                    'placeId'=>$airportActive['poiid'],
                                    'location'=>[
                                        'lat'=>$active[$a_k+1]['poi_lat'],
                                        'lng'=>$active[$a_k+1]['poi_lng'],
                                    ],
                                ];
                            }else{
                                $from = $to;
                            }
                            //还原数组
                            //$active = array_reverse($active);
                        }
                        if(in_array($t_v,[1,2])){
                            if(empty($airportActive)){
                                continue;
                            }else{
                                $pois = [];
                                $activities[] = [
                                    'id'=>$airportActive['id'],
                                    'type'=>$this->getTransportType($t_v),
                                    'carType'=>$carType,
                                    'city'=>$airportActive['cityId'],
                                    'from'=>$from,
                                    'to'=>$to,
                                    'pois'=>$pois
                                ];
                                continue;
                            }
                        }
                        if(in_array($t_v,[3,4,5,6,8])){//交通类型 市内半日 市内一日 周边一日 长途
                            $validLatLng = [];
                            foreach ($active as $a_k=>$a_v){
                                //此类型包含 除其他以外的其他分类
                                //如果存在接送机 会通过以上步鄹移除机场poi
                                //若不存在接送机 机场poi也会计算到行程路线
                                if($a_v['activeType']!=6){
                                    //机场类型
                                    if(in_array($a_v['activeType'],[2,3]) && !empty($a_v['airport_lat']) && !empty($a_v['airport_lng'])){
                                        $a_v['lat'] = $a_v['airport_lat'];
                                        $a_v['lng'] = $a_v['airport_lng'];
                                        $validLatLng[] = $a_v;
                                    }elseif(!empty($a_v['poi_lat']) && !empty($a_v['poi_lat'])){
                                        $validLatLng[] = $a_v;
                                    }
                                }
                            }

                            if(empty($validLatLng)){
                                continue;
                            }else{
                                $start_poi = array_shift($validLatLng);
                                $from = [
                                    'cityid'=>$start_poi['cityId'],
                                    'location'=>[
                                        'lat'=>$start_poi['poi_lat'],
                                        'lng'=>$start_poi['poi_lng'],
                                    ],
                                ];
                                $pois = [];
                                if(count($validLatLng)>0){
                                    $end_poi = array_pop($validLatLng);
                                    $to = [
                                        'cityid'=>$end_poi['cityId'],
                                        'location'=>[
                                            'lat'=>$end_poi['poi_lat'],
                                            'lng'=>$end_poi['poi_lng'],
                                        ],
                                    ];
                                    if(count($validLatLng)>0){
                                        foreach ($validLatLng as $valid_k=>$valid_v){
                                            $pois[] = ['location'=>[
//                                                'title'=>$valid_v['poiname'],
                                                'lat'=>$valid_v['poi_lat'],
                                                'lng'=>$valid_v['poi_lng']
                                            ]];
                                        }
                                    }
                                }else{
                                    $to = $from;
                                }
                                $activities[] = [
                                    'id'=>$start_poi['id'],
                                    'type'=>$this->getTransportType($t_v),
                                    'carType'=>$carType,
                                    'city'=>$start_poi['cityId'],
                                    'from'=>$from,
                                    'to'=>$to,
                                    'pois'=>$pois
                                ];
                            }
                        }
                    }
                }

                $resArr[] = [
                    "id"=>$s_value['id'],
                    "time"=>$s_value['time'],
                    "fixed"=>$s_value['return_journey'],
                    "activities"=>$activities
                ];
            }
        }
        return $resArr;
    }

    //测试订单系统的包车核价
    public function getOrderSystemTransportData($activitiesSnap)
    {
        if(empty($activitiesSnap)){
            return [];
        }else{
            $result = json_decode($activitiesSnap,true);
        }
        //获取所有日期
        $days = array_column($result,'time');
        $activities = [];
        //获取汇率
        $exchange = db('exchange')->select();
        foreach ($days as $day_k=>$day_v){
            $activities[$day_k]['time'] = $day_v;
            $activities[$day_k]['hasReturn'] = false;
            $activities[$day_k]['children'] = [];
            foreach ($result as $a_value){
                if(isset($a_value['errMessage'])) continue;
                if($a_value['time']==$day_v){
                    $a_value['displayString'] = $a_value['displayString']??"";
                    $a_value['displayString'] = empty($a_value['displayString'])?"":(explode('-',$a_value['displayString'])[1]??"");
                    $a_value['hasReturn'] = false;
                    $exchange_rate = 1;
                    foreach ($exchange as $exchange_k=>$exchange_v){
                        if($exchange_v['currency_code']==$a_value['currency']){
                            $exchange_rate = $exchange_v['exchange_rate'];
                            break;
                    }
                }
                    $a_value['totalAmountCNY'] = ceil($exchange_rate*$a_value['totalAmount']);
                    $activities[$day_k]['children'][] = $a_value;
                }
            }
        }
        return $activities;
    }

    public function packagePricingData($tripData,$transportData)
    {
        if(empty($tripData)){
            return $tripData;
        }
        //根据包车的数量判断总格子数
        $total_td_num = 0;
        $currencySymbols = (new Common())->getCurrencySymbols();
        foreach ($tripData as $key=>$value){
            //自驾
            $tripData[$key]['transport_pricing'] = [];
            $tripData[$key]['trans_count'] = 1;
            if(!empty($transportData)){
                    foreach($transportData as $k=>$v){
                        if($value['time']==$v['time']){
                            $transport_pricing = [];
                            $transport_pricing = array_merge($v['children'],$transport_pricing);
                            if(!empty($transport_pricing)){
                                array_walk($transport_pricing ,function ($arr,$index) use (&$transport_pricing,$currencySymbols){
                                    $transport_pricing[$index]['currency_symbol'] = $currencySymbols[$arr['currency']] ?? '';
                                });
                            }
                            $tripData[$key]['transport_pricing'] = $transport_pricing;
                            $tripData[$key]['trans_count'] = count($transport_pricing)>0?count($transport_pricing):1;
                            $total_td_num += $tripData[$key]['trans_count'];
                            break;
                        }
                    }
                }else{
                $total_td_num ++ ;
                    continue;
            }

        }


        foreach ($tripData as $trans_k=>$trans_v){
            //每日格子数至少为1 当日没有包车则默认为1
            $tripData[$trans_k]['total_td_num'] = $total_td_num;
        }

        //匹配酒店 租车 和包车的单元格
        $index_time = array_column($tripData,"time");
        $time_index = array_flip(array_filter($index_time));
        foreach ($tripData as $t_key=>$t_value){
            //酒店单元格
            $tripData[$t_key]['hotel_td_num'] = 0;
            if($t_value['hotel_show']==1 && !empty($t_value['hotel_time'])){
                $count= count($t_value['hotel_time']);
                for ($i = 0;$i<$count;$i++){
                    if(isset($time_index[$t_value['hotel_time'][$i]])){
                    $tripData[$t_key]['hotel_td_num'] += $tripData[$time_index[$t_value['hotel_time'][$i]]]['trans_count'];
                    }
                }
            }
            $tripData[$t_key]['hotel_td_num'] = $tripData[$t_key]['hotel_td_num']>0?$tripData[$t_key]['hotel_td_num']:1;
            //租车单元格
            $tripData[$t_key]['drive_td_num'] = 0;
            if($t_value['drive_flag']==1 && !empty($t_value['drive_time'])){
                $count= count($t_value['drive_time']);
                for ($i = 0;$i<$count;$i++){
                    if(isset($time_index[$t_value['drive_time'][$i]])){
                    $tripData[$t_key]['drive_td_num'] += $tripData[$time_index[$t_value['drive_time'][$i]]]['trans_count'];
                    }
                }
            }
            $tripData[$t_key]['drive_td_num'] = $tripData[$t_key]['drive_td_num']>0?$tripData[$t_key]['drive_td_num']:1;
        }

        return $tripData;
    }

    public function getTestTripData($id = 604){
        $priceTable = $this->priceTable($id);
	    $post_data = $this->orderTransportApiData($id);
        $transportData = $this->getOrderSystemTransportData($id);
        $tripData = $this->packagePricingData($priceTable,$transportData);
        $tripData = $this->getTripPriceTableData($tripData);
        echo "<pre>";
        var_dump($post_data,$transportData,$tripData);
        echo "</pre>";
        exit;
    }


    //修改价格
    public function changePriceTable(){
        $post = request()->post();
        $schedule_id = $post['schedule_id'];
        $type = $post['type'];
        $data = $post['data'];
        $name = isset($post['name']) ? $post['name'] : '';

        $model = new DaypriceModel();

        if(empty($schedule_id)){
            return $this->error("缺少id");
        }
        if($name==''){
            return $this->error("缺少name");
        }

        $priceData = db("dayprice")->where("groupid",$schedule_id)->find();
        if(empty($priceData)){//不存在时新增
            db('dayprice')->insert(['groupid'=>$schedule_id]);
        }

        $whereArr = ['groupid'=>$schedule_id];
        $updateData = [];
        if($type=='airport'){//航班信息
            $updateData[$name] = json_encode($data,JSON_UNESCAPED_UNICODE);
            $model->allowField(true)->save($updateData,$whereArr);
        }elseif($type=='hotel'){//酒店信息
            $alldayhotel = $post['alldayhotel'];
            $dayArr = explode(",",$alldayhotel);
            $updateData[$name] = $data;
            foreach ($dayArr as $v) {
                $model = new DaypriceModel();
                $daypriceInfo = $model->where("groupid",$v)->find();
                if(empty($daypriceInfo)){//不存在时新增
                        $updateData['groupid'] = $v;
                        $model->allowField(true)->insert($updateData);
                    }else{
                        $whereArr = ['groupid'=>$v];
                        $model->allowField(true)->save($updateData,$whereArr);
                    }
                }

        }elseif($type=='drive'){//租车信息
            $alldaydrive = $post['alldaydrive'];
            $dayArr = explode(",",$alldaydrive);
            $updateData[$name] = $data;
            if($name=='driveDetail'){
                foreach ($dayArr as $k=>$v) {
                    if(false==db("dayprice")->where("groupid",$v)->find()){//不存在时新增
                        $updateData['groupid'] = $v;
                        $model->allowField(true)->insert($updateData);
                    }else{
                        $whereArr = ['groupid'=>$v];
                        $model->allowField(true)->save($updateData,$whereArr);
                    }
                }
            }else{
                $model->allowField(true)->save($updateData,$whereArr);
            }
        }elseif($type=='other') {//其他信息
            $updateData[$name] = $data;
            if($name=='insurancePrice' || $name=='insuranceDetail'){
                $schedule = db("schedule")->where("id",$schedule_id)->field("groupid")->find();
                $tripid = $schedule['groupid'];

                $tripModel = new tripModel();
                $tripModel->allowField(true)->save($updateData,['id'=>$tripid]);
            }else{
                $model->allowField(true)->save($updateData,$whereArr);
            }
        }

        return $this->success("修改成功");
    }

    //保存总价
    public function saveTotalPrice(){
        $post = request()->post();
        $tripid = $post['tripid'];
        $totalPrice = $post['total_price'];

        $trip = db("trip")->where("id",$tripid)->field("total_price")->find();

        if($trip['total_price']!==$totalPrice && $totalPrice>0){
            $model = new tripModel();
            unset($post['tripid']);
            if(false==$model->allowField(true)->save($post,['id'=>$tripid])){
                return $this->error("保存总价失败");
            }else{
                return $this->success("修改成功");
            }
        }else{
            return $this->success("修改成功");
        }
    }
    //保存利率
    public function updatePriceRate()
    {
        $post = request()->post();
        $tripid = $post['tripid'];
        $ratePost = $post['ratePost']??"";
        $ratePost = json_decode($ratePost,true);
        $trip = db("trip")->where("id",$tripid)->find();
        if(empty($tripid) || empty($trip) || empty($ratePost) || !is_array($ratePost)){
            return $this->error("请求错误");
        }
        $updData = [];
        $total_sale_price = 0;
        $salePrice = [];
        foreach ($ratePost as $key=>$value){
            $updData[$value['name']] = $value['value'];
            $regionPriceKey = explode("_",$value['name'])[0];
            $salePrice[] = ceil($trip[$regionPriceKey]*$value['value']);
            $total_sale_price += ceil($trip[$regionPriceKey]*$value['value']);
        }
        if(empty($updData)){
            return $this->error("参数为空");
        }else{
            $updData['total_sale_price'] = $total_sale_price;
        }

        $model = new tripModel();
        if(false==$model->allowField(true)->save($updData,['id'=>$tripid])){
            return $this->error("修改失败");
        }else{
            return $this->success("修改成功",'',['salePrice'=>$salePrice,'total_sale_price'=>$updData['total_sale_price']]);
        }
    }
    //渲染数据表数据
    public function getTripPriceTableData($tripData){
        $schedule_ids = array_column($tripData,'id');
        if(!empty($schedule_ids)){
            $dayPrice = db("dayprice")->where(['groupid'=>['in',$schedule_ids]])->select();
            $schedule_index = array_flip($schedule_ids);
            if(!empty($dayPrice)){
                foreach ($dayPrice as $key=>$value){
                    $tableAirport = json_decode($value['airport_json'],true);
                    $tripAirport = $tripData[$schedule_index[$value['groupid']]]['airport'];

                    //机场匹配
                    foreach ($tripAirport as $air_key=>$air_value){
                        $tripAirport[$air_key]['detail'] = $tableAirport[$air_key][1]??"";
                        $tripAirport[$air_key]['price'] = $tableAirport[$air_key][2]??0;
                    }
                    $value['airportPrice'] = $tripAirport;
                    $tripData[$schedule_index[$value['groupid']]]['tableData'] = $value;
                    $tripData[$schedule_index[$value['groupid']]]['airport']=$tripAirport;
                }
            }
        }
        return $tripData;
    }

    //更新司导返程配置
    public function updReturnJourney()
    {
        $post = request()->post();
        $day_id = $post['day_id'];
        $status = $post['status'];

        $res = db("schedule")->where(['id'=>$day_id])->update(['return_journey'=>$status]);
        if($res!==false){
            if($status==2){
                $this->success("新增司导返程成功");
            }else{
                $this->success("删除司导返程成功");
            }
        }else{
            $this->error("设置失败");
        }
    }

    //ajax 拖拽active保存新groupid
    public function changeActiveDay(){
        $post = $this->request->post();
        $active_id = intval($post['active_id']);
        $schedule_id = intval($post['schedule_id']);
        $active_id_list = $post['active_id_list'];
        $where['id'] = $active_id;

        $activeModel = new activeModel();
        $active = $activeModel->where($where)->field("groupid")->find();
        $groupid = intval($active['groupid']);
        $activeData = $activeModel->where('groupid',$groupid)->field("id")->order("displayorder asc")->select();
        $prev_id = 0;
        $next_id = 0;
        //查询原节点前后节点id
        foreach ($activeData as $k=>$v) {
            if($v['id']==$active_id){
                if($k>0){
                    $prev_id = $activeData[$k-1]['id'];
                }
                if($k<(count($activeData)-1)){
                    $next_id = $activeData[$k+1]['id'];
                }
            }
        }

        $error = false;
        if($groupid!==$schedule_id){
            //修改变动节点的父id
            $res = $activeModel->where($where)->update(['groupid'=>$schedule_id]);
            if(false==$res){
                $error = true;
            }
        }

        //排序
        $active_id_Arr = explode(",",$active_id_list);
        $active_id_Arr = array_filter($active_id_Arr);
        $num = 1;
        foreach ($active_id_Arr as $k=>$v) {
            db("active")->where("id",$v)->update(['displayorder'=>$num]);
            $num++;
        }
        if($error){
            return $this->error("修改失败");
        }else{
            return $this->success("修改成功",'',['prev_id'=>$prev_id,'next_id'=>$next_id]);
        }
    }
    /**
     * 设置快速行程分段
     */
    public function setsectiontransport()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $trip = db("trip")->find($id);
        if(empty($trip)){
            return $this->error('行程信息有误');
        }
        //获取行程原始数据
        list($trip_index_arr,$schedules) = $this->getTripScheduleData($id);
        $section_json = json_decode($trip['section_json'],true);
        $section_json = !empty($section_json)?$section_json:[];
        if(!empty($section_json)){
            $index = input("index","");
            if($index==""){
                return $this->error("请求错误！");
            }
            //分段节点数据
            $section_json = (new ProductCtl())->getProductSectionJsonData($section_json,$schedules);
            $schedules = (new ProductCtl())->getSectionTransport($section_json[$index],$schedules);
            $trip_index_arr = [];
            foreach ($schedules as $key=>$value){
                foreach ($value['children'] as $k=>$v){
                    $trip_index_arr[] = $key."-".$k;
                }
            }
            $section_json = [$section_json[$index]];
            $transport_json = json_decode($trip['section_trans_json'],true);
            $transport_json = !empty($transport_json)?$transport_json:[];
            //判断节点是否可选
            if(isset($transport_json[$index])){
                $transport_arr = (new ProductCtl())->deconstructTransJson($transport_json[$index],$trip_index_arr);
                foreach ($schedules as $key=>$value){
                    foreach ($value['children'] as $child_key=>$child_value){
                        if(in_array($key.'-'.$child_key,$transport_arr)){
                            $schedules[$key]['disabled'] = true;
                            $schedules[$key]['children'][$child_key]['disabled'] = true;
                        }
                    }
                }
            }else{
                foreach ($schedules as $key=>$value){
                    foreach ($value['children'] as $child_key=>$child_value){
                        $schedules[$key]['disabled'] = false;
                        $schedules[$key]['children'][$child_key]['disabled'] = false;
                    }
                }
            }
        }else{
            return $this->error("请求错误！");
        }
        //展示交通列表
        if(isset($transport_json[$index])){
            $transList = $this->getDaysByTransJson($transport_json[$index],$schedules);
        }else{
            $transList = [];
        }
        $this->assign("transList",$transList);
        $this->assign('trip',$trip);
        $this->assign('index',$index);
        $this->assign('transport',$this->getTransportTitle());
        $this->assign("schedules",$schedules);
        $this->assign("sectionList",$section_json);
        return $this->fetch();
    }
    /**
     * 设置快速行程分段
     */
    public function setsection()
    {
        $trip_id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $trip = db("trip")->find($trip_id);
        if(empty($trip) || empty($trip_id)){
            return $this->error('行程信息有误');
        }
        //获取行程原始数据
        list($trip_index_arr,$schedules) = $this->getTripScheduleData($trip_id);

        try{
            $section_json = json_decode($trip['section_json'],true);
            $section_json = !empty($section_json)?$section_json:[];
            //所有节点均已设置
            $hasNotDisabled = false;
            if(!empty($section_json)){
                $section_arr = (new ProductCtl())->deconstructSectionJson($section_json,$trip_index_arr);
                foreach ($schedules as $key=>$value){
                    foreach ($value['children'] as $child_key=>$child_value){
                        if(in_array($key.'-'.$child_key,$section_arr)){
                            $schedules[$key]['disabled'] = true;
                            $schedules[$key]['children'][$child_key]['disabled'] = true;
                        }
                    }
                }
                //判断是否所有节点均为已设置
                foreach ($schedules as $key=>$value){
                    if($hasNotDisabled){
                        break;
                    }
                    foreach ($value['children'] as $child_key=>$child_value){
                        $disabled = $child_value['disabled']??false;
                        if(!$disabled){
                            //存在节点未设置
                            $hasNotDisabled = true;
                            break;
                        }
                    }
                }
                //分段节点数据
                $section_json = (new ProductCtl())->getProductSectionJsonData($section_json,$schedules);
                //包含具体交通类型的section
                $section_trans_json = json_decode($trip['section_trans_json'],true);
                $section_trans_json = !empty($section_trans_json)?$section_trans_json:[];
                $section_json = (new ProductCtl())->getProSecTransJsonData($section_json,$section_trans_json);
            }else{
                $hasNotDisabled = true;
            }
            $this->assign('trip',$trip);
            $this->assign('transport',$this->getTransportTitle());
            $this->assign("schedules",$schedules);
            $this->assign("sectionList",$section_json);
            $this->assign("hasNotDisabled",$hasNotDisabled);
        }catch(\Exception $e){
            if(strpos($e->getMessage(),'Undefined offset')!==false){
                //清空用车配置
                db('trip')->where(['id'=>$trip['id']])->update(['section_json'=>'','section_trans_json'=>'']);
            }
        }
        return $this->fetch();
    }
    //获取行程的原始节点数据
    public function getTripScheduleData($tripId)
    {
        $schedules = Db::name('schedule')->field("id,displayorder,time,groupid,title")->where('groupid',$tripId)->order('displayorder')->select();
        $schedule_ids = array_column($schedules,"id");
        if(!empty($schedule_ids)) {
            $activeList = db('active a')
                ->join("city c", "c.id=a.cityid", 'left')
                ->join("poi p", "p.id=a.poiid", 'left')
                ->join("schedule s", "a.groupid=s.id", 'left')
                ->field("s.time,a.id,a.title,a.poiname,a.groupid,a.activeType,a.time as startingTime,a.content as remark,a.displayorder,a.title,a.poiid,a.cityid as cityId,c.name as cityName,c.kbx_id as kbxCityId,a.airport_lat,a.airport_lng,p.lat,p.lng,a.poiid")
                ->where(['a.groupid' => ['in', $schedule_ids]])
                ->order('a.groupid,a.displayorder')
                ->select();
        }
        $trip_index_arr = [];
        foreach ($schedules as $key=>$value){
            $schedules[$key]['label'] = "第".$value['displayorder']."天【".$value['title']."】";
            $schedules[$key]['children'] = [];
            foreach ($activeList as $k=>$v){
                $v = (new SDModel())->getAirportInfo($v);
                if($v['groupid']==$value['id']){
                    $v['label'] = empty($v['poiname'])?$v['title']:$v['poiname'];
                    $schedules[$key]['children'][] = $v;
                    //计算节点个数
                    $trip_index_arr[] = $key.'-'.(count($schedules[$key]['children'])-1);
                }
            }
        }
        return [$trip_index_arr,$schedules];
    }
    //初步设置价格 【根据车型生成对应的数据，并未手动配置价格】
    public function setSectionPriceData()
    {
        $post = request()->post();
        $tripid = $post['trip_id']??0;
        $trip = db("trip")->where(['id'=>$tripid])->find();
        if(empty($trip)){
            $this->error("请求错误");
        }
        //获取当前分段的内容
        $price[] = [
            'car_type'=>$trip['carType'],
            'carTypeTitle'=>(new SDModel())->getCarTypeTitle($trip['carType']),
            'price'=> empty($trip['car_price_section'])?[]:json_decode($trip['car_price_section'],true)
        ];
        $this->success("获取成功",'',$price);
    }
    /**
     * 设置产品行程分段
     */
    public function setProductSection()
    {
        $post = request()->post();
        if(!empty($post)){
            $trip_id = isset($post['trip_id'])?$post['trip_id']:0;
            $days = isset($post['days'])?$post['days']:[];
            $items = isset($post['items'])?$post['items']:[];
            $trip = db("trip")->find($trip_id);
            if(empty($trip)){
                $this->error("行程信息有误");exit;
            }
            if(empty($days) || empty($items)){
                $this->error("参数信息有误");exit;
            }
            $transItem = [];
            reset($items);
            $start = current($items);
            $end = end($items);
            $transItem[] = [
                'start'=>$start,
                'end'=>$end,
                'transport'=>0,
                'isBatch'=>1
            ];
            //对项目进行排序
            $_json = json_decode($trip['section_json'],true);
            $_json = !empty($_json)?$_json:[];
            $transJsonData = array_merge($_json,$transItem);
            $index = count($transJsonData)-1;
            $trans_json = json_encode($transJsonData);
            $res = db("trip")->where(['id'=>$trip_id])->update(['section_json'=>$trans_json]);
            if($res!==false){
                //默认生成单段单日包车
                //$this->createOneProductSectionTransport($trip_id,$transJsonData[$index],$index);
                $this->success("保存成功","",$transJsonData);
            }else{
                $this->error("保存失败");
            }
        }else{
            $this->error("请求错误");exit;
        }
    }
    //清空分段设置
    public function delAllSection()
    {
        $post = request()->post();
        $id = $post['id']??0;
        $index = $post['index']??"";
        $product = db("trip")->find($id);
        if(empty($product)){
            $this->error("清空失败");
        }
        $res = db("trip")->where(['id'=>$id])->update(['section_json'=>"",'section_trans_json'=>'']);
        if($res){
            $this->success("清空成功");
        }else{
            $this->error("清空失败");
        }
    }
    //删除包车类型的设置
    public function delTransport()
    {
        $post = request()->post();
        $index = $post['index']??"";
        if(empty($post['id']) || $post['key']<0 || $index==""){
            $this->error("删除失败");
        }
        $trip = db("trip")->find($post['id']);
        if(empty($trip)){
            $this->error("请求错误");
        }
        if(empty($trip['section_trans_json'])){
            $this->error("暂未配置行程");
        }
        $transport_json = json_decode($trip['section_trans_json'],true);
        unset($transport_json[$index][$post['key']]);
        //如果当前段不存在包车 则删除当前设置
        if(empty($transport_json[$index])){
            unset($transport_json[$index]);
            //判断如果分段行程内的包车类型为空，则更新分段的包车类型
            $section_json = json_decode($trip['section_json'],true);
            $section_json[$index]['transport'] = 0;
            $section_json = json_encode($section_json);
            db("trip")->where(['id'=>$post['id']])->update(['section_json'=>$section_json]);
        }else{
            $transport_json[$index] = array_values($transport_json[$index]);
        }
        $transport_json = json_encode($transport_json);
        $res = db("trip")->where(['id'=>$post['id']])->update(['section_trans_json'=>$transport_json]);
        if($res!==false){
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }
    /**
     *通过车辆类型进行核价操作
     */
    public function getProductSectionPriceByCarType()
    {
        $post = request()->post();
        $tripid = $post['id']??0;
        $carType = $post['carType']??"";
        $trip = db("trip")->where(['id'=>$tripid])->find();
        if(empty($trip)){
            $this->error("请求错误");
        }
        if(empty($carType)){
            $this->error("请求错误");
        }
        //进行核价
        $carTypeList = explode(',',$carType);
        $priceData = [];
        foreach ($carTypeList as $car_k=>$car_v){
            $priceData[$car_k]['type'] = $car_v;
            $section_json = $this->checkSectionCarPrice($tripid,$car_v);
            if(!is_array($section_json)) $this->error("核价失败,原因是：".$section_json);
            $priceData[$car_k]['section_json'] = $section_json;
        }
        //核价完成
        if(!empty($priceData)){
            $this->success("核价成功",'',$priceData);
        }else{
            $this->error("核价失败");
        }
    }
    //组装包车核价数据
    public function checkSectionCarPrice($trip_id,$carType)
    {
        $trip = db("trip")->find($trip_id);
        $section_json = json_decode($trip['section_json'],true);
        $section_trans_json = json_decode($trip['section_trans_json'],true);
        list($trip_index_arr,$schedules)  = $this->getTripScheduleData($trip_id);
        //清空核价的数据
        db("trip")->where(['id'=>$trip_id])->update(['activitiesSnap'=>""]);
        foreach ($section_json as $key=>$value){
            $schedules_arr = (new ProductCtl())->getSectionTransport($value,$schedules);
            //核价的原始数据
            if(isset($section_trans_json[$key])){
                $section_carprice = (new ProductCtl())->packageSectionCarPirce($schedules_arr,$section_trans_json[$key],$carType);
                //调用接口进行核价
                list($totalAmount,$amountDetails,$currency) = (new ProductCtl())->getOrderSystemTransportDataByProduct($section_carprice,'trip',$trip_id);
                if($totalAmount<0){
                    return $amountDetails;
                }
            }else{
                list($totalAmount,$amountDetails,$currency) = [0,[],"USD"];
            }
            //将核价数据进行封装
            $section_json[$key]['totalAmount'] = $totalAmount;
            $section_json[$key]['currency'] = $currency;
            $section_json[$key]['amountDetails'] = $amountDetails;
        }
        return $section_json;
    }
    //保存自定义报价
    public function saveProductSectionPriceData()
    {
        $post = request()->post();
        $tripid = $post['id']??0;
        $carPriceData = $post['carPriceData']??[];
        $currency = $post['currency']??"";
        if(empty($carPriceData)){
            $this->error("请填写价格");
        }
        if(empty($currency)){
            $this->error("请选择派单价单位");
        }
        db::startTrans();
        try{
            foreach($carPriceData as $key=>$value){
                db("trip")->where(['id'=>$tripid])->update(['costCurrency'=>$currency,'car_price_section'=>json_encode($value['price'])]);
            }
            db::commit();
            $this->success("用车核价配置成功");
        }catch(Exception $e){
            db::rollback();
            $this->success("用车核价配置失败");
        }
    }
    //修改门票的状态
    public function setTicketStatus(){
        $post = $this->request->post();
        $active_id = $post['active_id'];
        $value = $post['value'];
        if($value==0){
            $upd['ticket_status'] = 1;
        }else{
            $upd['ticket_status'] = 0;
            $upd['ticket_json'] = '';
        }
        $res = db("active")->where("id",$active_id)->update($upd);
        if($res!==false){
            return $this->success("修改成功");
        }else{
            return $this->error("修改失败");
        }
    }
    //修改门票购买人数
    public function setTicketPeopleNum(){
        $post = $this->request->post();
        $active_id = $post['active_id'];
        $self_supplier_ticket = $post['self_supplier_ticket'];
        $ticketData = $post['ticketData'];//json格式
        if(empty($ticketData)){
            return $this->error("修改失败");
        }
        $res = db("active")->where("id",$active_id)->update(['ticket_json'=>$ticketData,'self_supplier_ticket'=>$self_supplier_ticket]);
        if($res!==false){
            return $this->success("修改成功");
        }else{
            return $this->error("修改失败");
        }
    }
    //更新选择门票的信息汇总
    protected function sumTicketDetailAndPrice($trip_id)
    {
        $schedules = Db::name('schedule')
            ->field("id,displayorder,time,groupid")
            ->where('groupid',$trip_id)
            ->order('displayorder')
            ->select();
        $schedule_ids = array_column($schedules,"id");
        if(!empty($schedule_ids)) {
            $activeList = db('active a')
                ->join("city c", "c.id=a.cityid", 'left')
                ->join("poi p", "p.id=a.poiid", 'left')
                ->join("schedule s", "a.groupid=s.id", 'left')
                ->field("a.ticket_json,a.ticket_status,a.title,
                    a.time as startingTime,a.content as remark,a.displayorder,
                    s.id as schedule_id,s.time,a.id,a.poiname,a.groupid,a.activeType,
                    a.cityid as cityId,c.name as cityName,c.kbx_id as kbxCityId,
                    a.airport_lat,a.airport_lng,p.lat,p.lng,a.poiid")
                ->where(['a.groupid' => ['in', $schedule_ids],'a.ticket_status'=>1])//默认选中了门票的节点
                ->order('a.groupid,a.displayorder')
                ->select();
            if(!empty($activeList)){
                //清空门票价格和信息
                db('dayprice')->where(['groupid'=>['in',$schedule_ids]])
                    ->update(['ticketDetail'=>'','ticketDetailToC'=>'','ticketPrice'=>0]);
                //获取汇率
                $exchange = db('exchange')->select();
                $ticketData = [];
                foreach ($activeList as $key=>$value){
                   if($value['ticket_status']==1){
                       //记录选择的门票信息
                       $ticket_json = empty($value['ticket_json'])?[]:json_decode($value['ticket_json'],true);
                       if(!empty($ticket_json)){
                            foreach ($ticket_json as $ticket_k=>$ticket_v){
                                if($ticket_v['number']< 1 ){
                                    continue;
                                }else{
                                    $ticketInfo = db("ticketprice tp")
                                        ->join("poi p",'p.id=tp.poiid','left')
                                        ->where(['tp.id'=>$ticket_v['ticket_id']])
                                        ->field('tp.*,p.name as poi_name')
                                        ->find();
                                    if(empty($ticketInfo)){
                                        continue;
                                    }else{
                                        $ticketInfo['number'] = $ticket_v['number'];
                                        //获取汇率
                                        foreach ($exchange as $ex_change){
                                            if($ex_change['currency_code']==$ticketInfo['currency']){
                                                $ticketInfo['exchange_rate'] = $ex_change['exchange_rate'];
                                                break;
                                            }
                                        }
                                        $ticketInfo['total_price'] = ceil($ticket_v['number']*$ticketInfo['exchange_rate']*$ticketInfo['sale_price']);
                                        $ticketData[$value['schedule_id']][] = $ticketInfo;
                                    }
                                }
                            }
                       }
                   }
                }
                if(!empty($ticketData)){
                    foreach ($ticketData as $ticket_key=>$ticket_value){
                        if(empty($ticket_value)) continue;
                        foreach ($ticket_value as $child_k=>$child_v){
                            $schedule_ticket = db('dayprice')->where(['groupid'=>$ticket_key])->find();
                            //此处样式不可随意更改 会影响前端显示 不能回车换行和进行缩进
                            $update_ticket['ticketDetail'] = $schedule_ticket['ticketDetail'].$child_v['poi_name'].$child_v['name'].":".$child_v['number'].'张
单价:'.$child_v['sale_price'].'【'.$child_v['currency'].'】
总价:'.$child_v['total_price'].'【RMB】
                            ';
                            $update_ticket['ticketDetailToC'] = $schedule_ticket['ticketDetailToC'].$child_v['poi_name'].$child_v['name'].":".$child_v['number'].'张
                            ';
                            $update_ticket['ticketPrice'] = $schedule_ticket['ticketPrice']+$child_v['total_price'];
                            db('dayprice')->where(['groupid'=>$ticket_key])->update($update_ticket);
                        }
                    }
                }
            }
        }
    }
    //检查自动建单数据是否完整
    protected function checkAutoCreateOrderComplete($tripid)
    {
        $msg = (new TripApi())->checkTripDataComplete($tripid);
        return $msg;
    }
    //创建行程表格的每日数据
    protected function createDayPriceData($schedule)
    {
        if(empty($schedule)) return false;
        foreach ($schedule as $key => $value) {
            if(db('dayprice')->where(['groupid'=>$value['id']])->find()){
                continue;
            }else{
                db('dayprice')->insert(['groupid'=>$value['id']]);
            }
        }
    }
    //自动建单
    public function createPaidCustomMadeOrder()
    {
        $post = request()->post();
        $tripid = $post['id']??0;
        //检查数据完整性
        $checkMsg = $this->checkAutoCreateOrderComplete($tripid);
        if(!is_array($checkMsg)) return $this->error($checkMsg);
        //验证用户信息
        $userphone = $checkMsg['country_code'].$checkMsg['phone'];
        $member = db('member')
            ->where('member_phone',$userphone)
            ->find();
        if(!empty($member)){
            $member_id = $member['member_id'];
        }else{
            //注册
            $shu= (new MemberApi())->register(['country_code'=>$checkMsg['country_code'],'telphone'=>$checkMsg['phone']]);
            $member_id = $shu['data']['member_id']??0;
        }
        if(empty($member_id)) $this->error("创建用户失败");
        //获取当前管理员的id
        $admin_id = Cookie::get('admin');
        //后台建单预订人信息
        $member = ['member_id'=>$member_id,'member_username'=>$userphone];
        //后台直接下单的状态
        $statusData = [
            'statusPhp'=>[
                'orderStatus'=>2,//已支付状态
                'finishedCondition'=>0,//表单已完善
            ]
        ];
        $trip = (new TripApi())->getAutoCreateOrderData($tripid,$member,$statusData,$admin_id);
        //查看日志
        if(empty($trip)){
            $this->error("自动建单失败");
        }
        //后台建单 状态均为已支付
        $trip['paid'] = true;
        //推送到订单系统建单
        $result = (new TripApi())->pushCustomMadeOrder($trip,$member_id,true);
        if(!is_array($result)){
            $this->error($result);
        }else{
            $this->success("自动建单成功,请前往订单系统查看");
        }
    }
    //确认行程定制完成
    public function adminConfirmOrderComplete()
    {
        $post = request()->post();
        $tripid = $post['id'] ?? 0;
        $trip = db('trip')->where(['id'=>$tripid])->find();
        if(empty($tripid) || empty($trip)){
            return $this->error('行程信息有误');
        }
        //检查数据完整性
        $checkMsg = $this->checkAutoCreateOrderComplete($tripid);
        if(!is_array($checkMsg)) return $this->error($checkMsg);
        $res = db('trip')->where(['id'=>$tripid])->update(['admin_confirm'=>1]);
        if($res!==false){
            //生成行程CDK
            $this->createCustomTripCDK($tripid);

            return $this->success('行程已确认定制完成,请通知用户支付或完成建单');
        }else{
            return $this->error('行程确认失败，请稍后重试');
        }
    }
    //保存每日的简要说明
    public function saveDayDescription()
    {
        $post = request()->post();
        $sid = $post['schedule_id']??0;
        $value = $post['value']??'';
        $schedule = db('schedule')->find($sid);
        if(empty($sid) || empty($schedule)) return $this->error('当日数据不存在');
        $res = db('schedule')->where(['id'=>$sid])->update(['day_description'=>$value]);
        if($res!==false){
            return $this->success('保存成功');
        }else{
            return $this->error('简要说明保存失败');
        }
    }
    
    //获取特定账户的定制列表
    public function cooprationTripList()
    {
        $post = $this->request->post();
        //分页bug处理
        $temp_page=request()->param('page');
        if(isset($temp_page)){
            //条件从缓存取出
            $post = Cookie::get('cooprationtriplist');
        }else{
            //把条件写入缓存
            Cookie::set('cooprationtriplist',$post);
        }

        $where = [];
        $where['t.use_type'] = 2;
        $where['t.adminid'] = Cookie::get('admin');
        $tripname = $post['tripname']??"";
        if($tripname) $where['t.name'] = ['like','%'.$tripname.'%'];
        $trip = Db::name('trip')
            ->alias("t")
            ->join("admin a",'a.id=t.adminid',"left")
            ->where($where)
            ->field("t.*,a.nickname as admin")
            ->order('create_time desc')
            ->paginate(20);
        $this->assign('trip',$trip);
        $this->assign('wherelist',$post);

        return $this->fetch();
    }

    //详细定制页
    public function tripmakePartner(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        //更新门票信息
        $model = new tripModel();
        $weekarray=array("日","一","二","三","四","五","六");
        $trip = [];
        if($id > 0) {
            $trip = $model->where("id",$id)->find();
            //仅定制师有查看权限
            if(empty($id) || empty($trip)) return $this->error('对不起，该定制行程有误');
            $adminid = Cookie::get('admin');
            $tripAdminInfo = db('admin')->where('id',$trip['adminid'])->find();
            $adminInfo = db('admin')->where('id',$adminid)->find();
            if($tripAdminInfo['company_id']!==$adminInfo['company_id'] && empty($trip['is_template'])){
                return $this->error('对不起，暂无查看修改权限');
            }
            $trip['start_go_time'] = $trip['start_go_time']>0 ? date("Y-m-d",$trip['start_go_time']) : '';
            $tripid = $id;
            $schedule = db("schedule")->where("groupid",$id)->order("displayorder asc")->select();

            $day = 1;
            //默认显示遮罩
            $trip['is_show_shadow'] = 1;
            foreach ($schedule as $k=>$v) {
                $schedule_id = $v['id'];
                $active = db("active")
                    ->where("groupid",$schedule_id)
                    ->order("displayorder asc")
                    ->field("id,title,poiname,poiid,cityid,activeType,airport_lat,airport_lng")
                    ->select();

                if(!empty($active)){
                    foreach ($active as $k_a=>$v_a) {
                        if(!empty($v_a['cityid']) && $v_a['cityid']>0){
                            $where['deleted'] = 0;
                            $where['groupid'] = $v_a['cityid'];

                            $poiArr = [];
                            if($v_a['activeType']==1){//POI
                                $where['typeid'] = ['in',[1,2,3,4,6]];//1景点，3演出赛事，4限时活动，6其他，11美食
                                $poiArr = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name")->select();
                            }elseif($v_a['activeType']==2 || $v_a['activeType']==3){//接机 送机
                                $airportData = $this->kbxGetAirport($v_a['cityid']);
                                $airport = [];
                                foreach ($airportData as $k_air=>$v_air) {
                                    $airportName = (isset($v_air['nameen']) && $v_air['nameen']!=='') ? $v_air['name']."(".$v_air['nameen'].")" : $v_air['name'];
                                    $airport[] = ['id'=>$v_air['id'],'name'=>$airportName];
                                    $poiArr = $airport;
                                }
                            }elseif($v_a['activeType']==4){//酒店
                                $where['typeid'] = 5;//酒店
                                $poiArr = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name")->select();
                            }elseif($v_a['activeType']==5){//特色体验

                            }elseif($v_a['activeType']==6){//其他

                            }elseif($v_a['activeType']>10){
                                $where['typeid'] = $v_a['activeType'];
                                $poiArr = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name")->select();
                            }

                            $active[$k_a]['poiArr'] = $poiArr;

                            //加入距离
                            $activeDistance = $this->getActiveDistance($k_a,$active);
                            $active[$k_a]['limit'] = $activeDistance;
                        }else{
                            $active[$k_a]['poiArr'] = [];
                        }
                    }
                }

                $schedule[$k]['active'] = $active;
                $schedule[$k]['dayNum'] = $day;
                $schedule[$k]['week'] = "周".$weekarray[date("w",strtotime($v['time']))];

                $_trans_type_arr = [];
                if(!empty($v['transport_typeids'])){
                    //不显示遮罩
                    $trip['is_show_shadow'] = 0;
                    $trans_type_arr = explode(",",$v['transport_typeids']);
                    if(!empty($trans_type_arr)){
                        foreach ($trans_type_arr as $value){
                            $trans_type_item = [
                                'id'=>$value,
                                'title'=>$this->getTransportTitle($value),
                            ];
                            $_trans_type_arr[] = $trans_type_item;
                        }
                    }
                }
                $schedule[$k]['transportList'] = $_trans_type_arr;

                $day++;
            }
            //核价数据
            $this->assign('totalHotelPrice',$trip['totalHotelPrice']);
            $this->assign('totalAirportPrice',$trip['totalAirportPrice']);
            $this->assign('totalDrivePrice',$trip['totalDrivePrice']);
            $this->assign('totalTransPrice',$trip['totalTransPrice']);
            $this->assign('airportPrice_btn',$trip['airportPrice_btn']);
            $this->assign('hotelPrice_btn',$trip['hotelPrice_btn']);
            $this->assign('drivePrice_btn',$trip['drivePrice_btn']);
            $this->assign('carPrice_btn',$trip['carPrice_btn']);

            $this->assign('schedule',$schedule);
            //生成dayprice记录
            $this->createDayPriceData($schedule);
            //当前定制处于未锁状态方可更新
            if($trip['isLocked']<1){
                //更新门票信息
                $this->sumTicketDetailAndPrice($tripid);
            }
            $priceTable = $this->priceTable($tripid);
            $transportData = $this->getOrderSystemTransportData($trip['activitiesSnap']);
            $tripData = $this->packagePricingData($priceTable,$transportData);
            $renderPriceData = $this->getTripPriceTableData($tripData);
            //var_dump(json_encode($renderPriceData));exit;
            $this->assign('priceTable',$renderPriceData);
            //获取用车核价
            $totalCarPriceCNY = 0;
            if(!empty($trip['car_price_section'])){
                $car_price_section = json_decode($trip['car_price_section'],true);
                //获取汇率
                $exchange = db('exchange')->where(['currency_code'=>$trip['costCurrency']])->find();
                if(!empty($exchange)){
                    foreach ($car_price_section as $car_price){
                        $totalCarPriceCNY += ceil($car_price*$exchange['exchange_rate']);
                    }
                }
            }
            $this->assign('totalCarPriceCNY',$totalCarPriceCNY);
        }else{
            $this->assign('airportPrice_btn',0);
            $this->assign('hotelPrice_btn',0);
            $this->assign('drivePrice_btn',0);
            $this->assign('carPrice_btn',0);
            $tripid = 0;
        }
        $where_city['type'] = "CITY";
        $where_city['deleted'] = 0;
        //按照中文名称排序
        $city_order = new \think\db\Expression("CONVERT(name USING gbk) asc");
        $city = db("city")->where($where_city)->field("id,name")->order($city_order)->select();
        $tripcustomer = db("tripcustomer")->where("tripid",$tripid)->find();

        $this->assign('city',$city);
        $this->assign('tripid',$tripid);
        $this->assign('trip',$trip);
        $this->assign('customer',$tripcustomer);
        //新建poi所需城市列表
        $ourcity = Db::name('city')->where(['deleted'=>0,'groupid'=>['neq',0]])->field('id,concat(name,"(",eng_name,")") as name')->order("sort_weight desc")->select();
        $this->assign('ourcity',$ourcity);

        //扩展包车
        $transport = $this->getTransportTitle();
        $this->assign('transport',$transport);


        //获取订单的来源列表
        $originList = (new KbxOther())->kbx_origin_list();
        $this->assign('originList',$originList);
        //渲染行程价格数据
        //获取国家电话区号
        $phoneCodeList = (new TripApi())->getCountryPhoneCode();
        $this->assign('phoneCodeList',$phoneCodeList);
        //关闭新建跳转地址
        $closeRedirectUrl = config('kbx_agent_url')."/#/customorder";
        $this->assign('closeRedirectUrl',$closeRedirectUrl);

        //货币类型
        $currencyCodeList = (new Common())->getCurrencyListByCity();
        $this->assign("currencyCodeList",json_encode($currencyCodeList));
        //获取税率
        $exchangeList = db('exchange')->select();
        $this->assign("exchangeList",json_encode($exchangeList));

        //POI分类 前期做了部分拆分 以至于需要单独设计
        $poiClassifyList = $this->getPoiClassifyList();
        $global_active_type_arr = (new ProductCtl())->getGlobalActiveTypeList();

        $this->assign("poiClassifyList",$poiClassifyList);
        $this->assign("global_active_type_arr",json_encode($global_active_type_arr));

        return $this->fetch();
    }

    //验证是否为合作方账号
    public function isPartnerUser(){
        $admin_id = Cookie::get('admin');
        $adminData = db("admin")->where("id",$admin_id)->find();
        $admin_cate_id = $adminData['admin_cate_id'];
        if($admin_cate_id==28){
            return true;
        }
        return false;
    }

    //前置方法 判断是否为模板定制
    public function checkIsTemplateTrip()
    {
        $get_trip_id = input('id',0);
        $post = request()->post();
        $active_id = $post['active_id']??0;
        $schedule_id = $post['schedule_id']??0;
        $trip_id = $post['tripid']??$get_trip_id;

        if(!empty($trip_id)){
            $trip = db('trip')->where('id',$trip_id)->find();
        }elseif(!empty($schedule_id)){
            $schedule = db('schedule')->where('id',$schedule_id)->find();
            if(!empty($schedule)){
                $trip = db('trip')->where('id',$schedule['groupid'])->find();
            }
        }elseif(!empty($active_id)){
            $active = db('active')->where('id',$active_id)->find();
            if(!empty($active)){
                $schedule = db('schedule')->where('id',$active['groupid'])->find();
                if(!empty($schedule)){
                    $trip = db('trip')->where('id',$schedule['groupid'])->find();
                }
            }
        }
        if(!empty($trip) && !empty($trip['is_template'])){
            $data = ['code'=>0,'msg'=>'该定制为模板，只可查看不允许修改'];
            $this->echoJs($data);
        }
    }

    //直接数据json数据
    protected function echoJs($data)
    {
        header('Content-type:application/json; charset=utf-8');
        echo json_encode($data,JSON_UNESCAPED_UNICODE);exit;
    }

    public function createTripByTemplate()
    {
        $post = request()->post();
        $temp_id = $post['temp_id']??0;

        $admin_id = Cookie::get('admin');
        $result = (new TripApiModel())->createCustomMadeByTemplate($temp_id,$admin_id);
        if(!is_array($result)){
            return $this->error($result);
        }else{
            return $this->success($result['msg'],'',['id'=>$result['id']]);
        }
    }

    //设置 取消 定制的模板
    public function updateTemplate()
    {
        $id = input('id',0);
        $value = input('value',0);

        $trip = db('trip')->find($id);
        if(empty($id) || empty($trip)) return $this->error('定制信息不存在');

        $res = db('trip')->where('id',$id)->update(['is_template'=>$value]);
        if($res!==false){
            $this->success('设置成功');
        }else{
            $this->success('设置失败');
        }
    }

    public function createCustomTripCDK($tripid)
    {
        if(empty($tripid)) return false;
        $trip = db('trip')->find($tripid);
        if(empty($trip)) return false;
        $cdk = db('tripcdk')->where(['trip_id'=>$tripid,'isdelete'=>0,'state'=>1])->find();
        //不存在就新增
        if(empty($cdk)){
            $admin_id = Cookie::get('admin');
            $day = $trip['days']>1?$trip['days'].' days':$trip['days'].' day';
            $endtime = strtotime($day,$trip['start_go_time']);
            $cdk_num = (new Tripcdk())->randomkeys();
            $res = db('tripcdk')->insert([
                'trip_id'=>$tripid,
                'endtime'=>$endtime,
                'admin_id'=>$admin_id,
                'CDK'=>$cdk_num,
                'state'=>1,
                'uptime'=>time()
            ]);
            //记录日志
            empty($res)?trace('tripcdk新增成功，tripid:'.$tripid.',cdk:'.$cdk_num):trace('tripcdk新增失败,tripid:'.$tripid);
        }
    }

    //保存快速定制的客户信息
    public function saveTripCustomerData()
    {
        $post = request()->post();
        $tripid = $post['tripid']??0;
        if(empty($tripid)) $this->result([],0,'行程信息不存在','json');
        $trip = db('trip')->find($tripid);
        $tripcustomer = db('tripcustomer')->where('tripid',$tripid)->find();
        if(empty($trip)) $this->result([],0,'行程信息不存在','json');

        if(empty($tripcustomer)){
            $res = db('tripcustomer')->insert($post);
        }else{
            $res = db('tripcustomer')->where('id',$tripcustomer['id'])->update($post);
        }
        if($res!==false){
            //新增商机
//          $post['opportunity_id'] = $trip['opportunity_id'];
//          $KbxOrder = new KbxOrder();
//          $bus_id = $KbxOrder->enterBusOpportunities($post);

            $this->result($post,1,'保存成功','json');
        }else{
            $this->result([],0,'保存失败','json');
        }
    }

    //重新设置最后一次分段
    public function resetLastSection()
    {
        $post = request()->post();
        $tripid = $post['id']??0;
        if(empty($tripid)) return $this->result([],0,'缺少行程ID','json');
        $trip = db('trip')->field('section_json')->find($tripid);
        if(empty($trip)) return $this->result([],0,'行程不存在','json');
        if(empty($trip['section_json'])) return $this->result([],0,'行程暂未设置分段','json');

        $section_json_arr = json_decode($trip['section_json'],true);
        unset($section_json_arr[count($section_json_arr)-1]);
        $section_json = empty($section_json_arr)?'':json_encode($section_json_arr);
        //删除最后一个分段的同时 置空所有的trans_json数据 防止数据错误
        $res = db('trip')->where('id',$tripid)->update(['section_json'=>$section_json,'section_trans_json'=>'']);
        if($res){
            return $this->result($res,200,'重设成功','json');
        }else{
            return $this->result([],0,'重设失败','json');
        }

    }

    //获取POI分类
    public function getPoiClassifyList()
    {
        $poiClassifyList = db('classify')
            ->field('classify_id as id,classify_name as name')
            ->where(['is_use'=>1,'classify_id'=>['gt',10]])
            ->select();
        array_unshift($poiClassifyList,['id'=>1,'name'=>'POI']);
        $poiClassifyList[] = ['id'=>6,'name'=>'其他'];
        return $poiClassifyList;
    }

    //采购expedia酒店
    public function joinExpediaHotel(Request $request)
    {
        if(!$request->isPost()) return $this->error('请以POST方式提交！');
        $validate = new Validate([
            ['trip_id','require','缺少trip_id参数'],
            ['hotel_id','require','缺少hotel_id参数'],
            ['hotel_json','require','缺少hotel_info信息'],
        ]);
        if(!$validate->check($request->post())){
            return $this->error($validate->getError());
        }

        //数据入库
        $post = $request->post();
        $post['hotel_name'] = $post['hotel_json']['hotel_name'] ?? '';
        $post['check_in'] = $post['hotel_json']['check_in'] ?? '';
        $post['check_out'] = $post['hotel_json']['check_out'] ?? '';
        $post['occupancy'] = $post['hotel_json']['occupancy'] ?? '';
        $post['total_price'] = $post['hotel_json']['computed_price']['totalPrice'] ?? 0;
        $post['hotel_json'] = json_encode($post['hotel_json']);
        $post['hotel_type'] = 'expedia';
        $post['create_time'] = time();
        $res = (new TripActiveHotel())->allowField(true)->insert($post);
        if($res){
            //判断是否存在酒店 否则手动添加酒店POI 且挂到当天的定制行程


            return $this->success('添加成功');
        }else{
            return $this->error('添加失败');
        }
    }

    //取消expedia酒店关联
    public function removeExpeidaHotel(Request $request)
    {
        if(!$request->isPost()) return $this->error('请以POST方式提交！');
        $validate = new Validate([
            ['id','require','缺少id参数'],
        ]);

        if(!$validate->check($request->post())){
            return $this->error($validate->getError());
        }

        $res = (new TripActiveHotel())->where(['id'=>$request->post('id')])->update([
            'is_delete'=>1,
            'delete_time'=>time()
        ]);
        if($res){
            return $this->success('删除成功');
        }else{
            return $this->error('删除失败');
        }

    }

    public function linkThirdHotel(Request $request)
    {
        return $this->fetch();
    }
}